Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an assertException in any of the Haskell test frameworks?

I'm writing some tests using HUnit and I would like to assert that a particular function throws an exception given a certain input. I can't find an assert function which provides the required functionality. Anyone know of a test framework that does?

like image 751
Sean Seefried Avatar asked May 27 '11 03:05

Sean Seefried


2 Answers

Although HUnit doesn't come with any exception assertions, it's easy to write your own:

import Control.Exception
import Control.Monad
import Test.HUnit

assertException :: (Exception e, Eq e) => e -> IO a -> IO ()
assertException ex action =
    handleJust isWanted (const $ return ()) $ do
        action
        assertFailure $ "Expected exception: " ++ show ex
  where isWanted = guard . (== ex)

testPasses = TestCase $ assertException DivideByZero (evaluate $ 5 `div` 0)
testFails  = TestCase $ assertException DivideByZero (evaluate $ 5 `div` 1)

main = runTestTT $ TestList [ testPasses, testFails ]

You can do something more fancy like using a predicate instead of explicit comparison if you like.

$ ./testex
### Failure in: 1                         
Expected exception: divide by zero
Cases: 2  Tried: 2  Errors: 0  Failures: 1

Note that evaluate here might get optimized away (see GHC ticket #5129), but for testing code in the IO monad this should work fine.

like image 106
hammar Avatar answered Oct 17 '22 05:10

hammar


You can use assertRaises from testpack.

like image 36
Patrick Marty Avatar answered Oct 17 '22 06:10

Patrick Marty