使用 QuickCheck 抛出异常时是否可以检查案例?

Is it possible to check cases when exception is thrown with QuickCheck?

假设我有一个函数应该在一种情况下计算一些值并且 否则抛出异常。我想使用 QuickCheck 来确保我的 函数行为正确,但是如何执行这种排序并不明显 检查。是否可能,如果是,如何检查某些异常 type 被抛出并且它包含有关其原因的正确信息?

确实ioProperty is the key to this sort of test. You will need to use it in combination with catch or try。这里我展示后者:

prop_exceptional :: Int -> Property
prop_exceptional n = ioProperty $ do
  result <- try . evaluate $ myDangerousFunction n
  return $ r === result
  where r | n == 0    = Left  MyException
          | otherwise = Right 42

很明显,myDangerousFunction 应该在得到 0 时抛出 MyException,否则 return 42。请注意有用的函数 evaluate,您需要使用它来评估 IO 上下文中的纯函数以捕获那里产生的异常。