Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

testing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...