How do I test for an error in Haskell?

我的未来我决定 提交于 2019-11-30 13:51:58

OP's solution defines assertException, but it looks like Test.HUnit.Tools.assertRaises from testpack is also usable here.

I added the msg argument to assertError to match how assertRaises works, and included selective imports so noobs like me can learn where commonly used things are imported from.

import Control.Exception (ErrorCall(ErrorCall), evaluate)
import Test.HUnit.Base  ((~?=), Test(TestCase, TestList))
import Test.HUnit.Text (runTestTT)
import Test.HUnit.Tools (assertRaises)

pos :: Int -> Int
pos x
   | x >= 0 = x
   | otherwise = error "Invalid Input"

instance Eq ErrorCall where
    x == y = (show x) == (show y)

assertError msg ex f = 
    TestCase $ assertRaises msg (ErrorCall ex) $ evaluate f

tests = TestList [
  (pos 0) ~?= 0
  , (pos 1) ~?= 1
  , assertError "Negative argument raises an error" "Invalid Input" (pos (-1))
  ]   

main = runTestTT tests

There are several ways to handle errors in Haskell. Here is an overview: http://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors

[Edit]

The first example shows how to catch errors, e.g.

half :: Int -> Int 
half x = if even x then x `div` 2 else error "odd"

main = do catch (print $ half 23) (\err -> print err)

That said, this kind of error handling is better suited for IO stuff, in pure code like yours Maybe, Either or something similar is usually a better choice. It could be as simple as...

pos :: Int -> Maybe Int
pos x
   | x >= 0 = Just x
   | otherwise = Nothing

tests = [pos 1 == Just 1
        ,pos (-1) == Nothing
        ,pos 2 == Just 2
        ,pos (-2) == Nothing
        ]

main = print $ and tests

... if you don't need an error type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!