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

前端 未结 3 1206
眼角桃花
眼角桃花 2020-12-16 15:11

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 p

相关标签:
3条回答
  • 2020-12-16 15:46

    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.

    0 讨论(0)
  • 2020-12-16 15:57

    You can use assertRaises from testpack.

    0 讨论(0)
  • 2020-12-16 15:59

    hspec (or more precisely hspec-expectations) has shouldThrow.

    0 讨论(0)
提交回复
热议问题