说我想要写的一些单元测试(!!)
功能。
my_prop xs n = ...
我想限制N到唯一有效的指标,我知道我可以做类似
my_prop xs n = (not.null) (drop n xs) ==> ...
但是,这使得它如此,绝大多数的产生情况是无效而被扔掉。 有没有一种方法,我可以做一些事情,以便快速检查产生xs
第一列表,并使用它的值只生成有效的情况下n
?
说我想要写的一些单元测试(!!)
功能。
my_prop xs n = ...
我想限制N到唯一有效的指标,我知道我可以做类似
my_prop xs n = (not.null) (drop n xs) ==> ...
但是,这使得它如此,绝大多数的产生情况是无效而被扔掉。 有没有一种方法,我可以做一些事情,以便快速检查产生xs
第一列表,并使用它的值只生成有效的情况下n
?
使用forAll
,你可以指定一个发电机为n
依赖于早期的参数,如
my_prop (NonEmpty xs) = forAll (choose (0, length xs - 1)) $ \n -> ...
你可以做一个发电机,仅创建有效的索引,并写入你的财产像
import Test.QuickCheck
import Test.QuickCheck.Gen
import System.Random
indices :: [a] -> Gen Int
indices xs = MkGen $ \sg _ -> fst $ randomR (0, length xs - 1) sg
my_prop :: [Char] -> Property
my_prop xs = not (null xs) ==> forAll (indices xs) (\i -> xs !! i /= '0')
消除Int
的说法。
正如丹尼尔·瓦格纳认为,一种可能性是创造我自己的数据类型,并给它一个Arbitrary
实例。
data ListAndIndex a = ListAndIndex [a] Int deriving (Show)
instance Arbitrary a => Arbitrary (ListAndIndex a) where
arbitrary = do
(NonEmpty xs) <- arbitrary
n <- elements [0..(length xs - 1)]
return $ ListAndIndex xs n
NonEmpty
是从自定义类型Test.QuickCheck.Modifiers
产生非空列表。