在任何Haskell测试框架中是否存在assertException?

时间:2011-05-27 03:06:41

标签: testing haskell

我正在使用HUnit编写一些测试,并且我想断言特定函数在给定某个输入的情况下抛出异常。我找不到提供所需功能的断言功能。有人知道测试框架吗?

3 个答案:

答案 0 :(得分:18)

虽然HUnit没有任何异常断言,但是编写自己的断言很容易:

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 ]

如果你愿意,你可以做一些更像是使用谓词而不是显式比较的东西。

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

请注意,此处的evaluate可能会被优化掉(请参阅GHC票证#5129),但是为了测试IO monad中的代码,这应该可以正常工作。

答案 1 :(得分:5)

您可以使用assertRaises中的testpack

答案 2 :(得分:0)

hspec(或更确切地说,hspec-expectations)有shouldThrow