Hedgehog withTests不生效:如何让属性测试运行10000次?
解决Hedgehog测试仅运行一次的问题
看起来你遇到的问题是Hedgehog属性没有按照预期执行多次测试用例,我来帮你排查可能的原因和对应的解决方案:
1. 调整withTests的测试次数设置
你当前设置的1000000000(10亿次)测试次数过于庞大,这可能触发Hedgehog的内部保护机制,或者导致tasty直接跳过大量测试。先把次数改成你实际需要的10000次试试:
hprop_SquareMonoid :: Property hprop_SquareMonoid = withTests 10000 . property . monoid $ Square <$> small2DGen
另外可以确认下Hedgehog.Checkers的monoid函数是否正确生成多组测试——它内部应该通过forAll生成随机值并验证monoid定律,如果这个函数本身逻辑有问题,也会导致测试仅执行一次。
2. 绕开tasty-discover手动包装测试树
tasty-discover通过hprop_前缀识别Hedgehog属性,但偶尔会因为版本兼容或配置问题出现识别异常。你可以手动定义测试树来验证:
module Spec where import Test.Tasty import Test.Tasty.Hedgehog (testProperty) import Hedgehog import Hedgehog.Checkers import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Lib -- 你的生成器和属性定义保持不变 make2D :: a -> a -> Point2D a make2D x y = Point2D { _x = x, _y = y } point2DGen :: (Gen a) -> Gen (Point2D a) point2DGen g = make2D <$> g <*> g small2DGen :: Gen (Point2D Int) small2DGen = point2DGen . Gen.integral $ Range.linearFrom (0 :: Int) (-10) 10 hprop_SquareMonoid :: Property hprop_SquareMonoid = withTests 10000 . property . monoid $ Square <$> small2DGen -- 手动定义测试树 tests :: TestTree tests = testGroup "Square Monoid Tests" [ testProperty "Square satisfies Monoid laws" hprop_SquareMonoid ]
然后在主入口Main.hs里运行这个测试树:
import Test.Tasty import Spec main :: IO () main = defaultMain tests
如果这样测试能正常运行10000次,那问题就出在tasty-discover的配置上,你可以检查它的版本或调整自动发现的规则。
3. 通过命令行强制指定测试次数
你也可以在运行测试时通过tasty的命令行参数,强制所有Hedgehog属性执行指定次数的测试:
cabal run test -- -j1 --hedgehog-tests=10000
这个参数会覆盖单个属性的设置,确保测试执行10000次。
4. 验证生成器的有效性
最后确认你的small2DGen确实能生成不同的随机值——如果生成器逻辑错误(比如总是返回同一个值),测试也会看起来只执行了一次。你可以在GHCi里测试生成器:
import Hedgehog import Spec main = sample small2DGen
运行后如果输出多个不同的Point2D值,说明生成器是正常的。
内容的提问来源于stack exchange,提问作者Julian Birch
相关产品推荐
相关产品推荐

