我正在使用QuickCheck
来测试以下程序:
{-# LANGUAGE TemplateHaskell #-}
import Test.QuickCheck
import Test.QuickCheck.All
elementAt :: (Integral b) => [a] -> b -> a
elementAt [x] _ = x
elementAt (x:xs) 1 = x
elementAt (x:xs) b = elementAt xs (b - 1)
prop_elementAt xs b = length xs > 0 && b >= 0 && b < length xs ==> elementAt xs (b + 1) == xs !! b
main = $(quickCheckAll)
虽然响应有所不同,但我不断收到消息
*** Gave up! Passed only x tests.
这是我应该关注的吗?或者测试输入的性质是否决定了QuickCheck的运行时间?
答案 0 :(得分:18)
==>
的工作方式是首先快速检查会为xs
和b
生成随机值,然后检查谓词length xs > 0 && b >= 0 && b < length xs
是否满足,然后才会检查该物业的可满足性。
由于它将生成多少测试用例存在限制,因此很多时候上述谓词不满足可能会发生。因此,在生成足够的有效测试用例(满足谓词)之前,quickcheck会放弃。
您应该将Arbitrary
实例声明为newtype,以仅生成满足这些谓词的测试用例。
{-# LANGUAGE TemplateHaskell #-}
import Test.QuickCheck
import Test.QuickCheck.All
elementAt :: (Integral b) => [a] -> b -> a
elementAt [x] _ = x
elementAt (x:xs) 1 = x
elementAt (x:xs) b = elementAt xs (b - 1)
prop_elementAt (Foo xs b) = elementAt xs (b + 1) == xs !! b
data Foo a b = Foo [a] b deriving (Show)
instance (Integral b, Arbitrary a, Arbitrary b) => Arbitrary (Foo a b) where
arbitrary = do
as <- listOf1 arbitrary -- length xs > 0
b <- choose (0,length as - 1) -- b >= 0 and b < length xs
return (Foo as $ fromIntegral b)
main = $(quickCheckAll)