You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell中使用monadicIO时如何用QuickCheck运行单个测试?

让QuickCheck仅执行一次无参数IO测试

你在使用Haskell的QuickCheck做测试时,遇到了无参数IO测试被默认执行100次的问题,示例测试代码如下:

prop_parseTest :: Property
prop_parseTest = monadicIO $ do
  run $ writeFile "temp.txt" "hello world!"
  content <- run $ readFile "temp.txt"
  assert $ content == "hello world!"

且你通过quickCheckAll执行测试:

return []
runTests = $quickCheckAll

main :: IO ()
main = qcTests runTests

qcTests :: IO Bool -> IO ()
qcTests tests = do
  passed <- tests
  if passed then exitSuccess
            else exitFailure

解决方法

使用QuickCheck提供的once函数修饰你的测试Property,它会强制该测试仅运行一次,不受默认100次测试次数的影响。

修改后的测试代码如下:

import Test.QuickCheck (once) -- 确保导入该函数

prop_parseTest :: Property
prop_parseTest = once $ monadicIO $ do
  run $ writeFile "temp.txt" "hello world!"
  content <- run $ readFile "temp.txt"
  assert $ content == "hello world!"

once函数的作用是将目标Property标记为单次执行,其他测试仍会遵循默认的运行次数设置,不会影响全局测试行为。

内容的提问来源于stack exchange,提问作者Terra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:10:28