6

Suppose I have a function that should calculate some value in one case and throw an exception otherwise. I would like to use QuickCheck to ensure my function behaves correctly, however is not obvious how to perform this sort of check. Is it possible and if yes, how to check that exception of certain type is thrown and it contains correct information about its cause?

Mark Karpov
  • 7,499
  • 2
  • 27
  • 62
  • 1
    I guess you are talking about `Control.Exception` right? In this case the obvious thing would be to go with [`catch`](https://hackage.haskell.org/package/base-4.8.1.0/docs/Control-Exception-Base.html#v:catch) and [`ioProperty`](https://hackage.haskell.org/package/QuickCheck-2.8.1/docs/Test-QuickCheck-Property.html#t:ioProperty) (for quickCheck) – Random Dev Oct 31 '15 at 12:48
  • @Carsten, good, `catch` or `try` combined with `ioProperty` should do the trick. – Mark Karpov Oct 31 '15 at 13:33

1 Answers1

2

Indeed ioProperty is the key to this sort of test. You will need to use it in combination with catch or try. Here I show the latter:

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

Quite obviously, myDangerousFunction should throw MyException whenever it gets 0 and return 42 otherwise. Note the useful function evaluate, which you need to use to evaluate pure function in IO context to catch exceptions produced there.

Mark Karpov
  • 7,499
  • 2
  • 27
  • 62