简体   繁体   中英

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

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
    ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM