How can I test Control.Monad.Except
(both guard results) a function like:
foo :: Double -> Double -> Except String Double
foo x y
| x < -10.0 = throwError "Invalid parameter"
| otherwise = pure $ x + y
using hunit
?
It's pretty straightforward to write some functions which use runExcept
to execute an Except
action and use ~?=
to check its results.
shouldThrow :: Eq e => Except e a -> e -> Test
m `shouldThrow` e = runExcept m ~?= Left e
shouldReturn :: Eq a => Except e a -> a -> Test
m `shouldReturn` x = runExcept m ~?= Right x
Example usage:
testFoo = TestList [
foo -11 2 `shouldThrow` "Invalid parameter",
foo 3 1 `shouldReturn` 4
]