我正在使用HUnit编写一些测试,我想断言特定函数在给定某个输入的情况下抛出异常.我找不到提供所需功能的断言功能.有人知道测试框架吗?
ham*_*mar 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 ]
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你可以做一些更像是使用谓词而不是显式比较的东西.
$ ./testex
### Failure in: 1
Expected exception: divide by zero
Cases: 2 Tried: 2 Errors: 0 Failures: 1
Run Code Online (Sandbox Code Playgroud)
请注意,evaluate这里可能会被优化掉(参见GHC票证#5129),但是为了测试IOmonad中的代码,这应该可以正常工作.
您可以使用assertRaises从testpack.