how to test import Control.Monad.Except with Hunit?

111 Views Asked by At

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?

1

There are 1 best solutions below

1
Benjamin Hodgson On BEST ANSWER

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
    ]