我希望能够确保函数在接收到无效值时会抛出错误。例如,假设我有一个仅返回正数的函数 pos:
pos :: Int -> Int
pos x
| x >= 0 = x
| otherwise = error "Invalid Input"
这是一个简单的例子,但我希望你能明白。
我希望能够编写一个测试用例,该测试用例会出现错误并认为它是通过测试。例如:
tests = [pos 1 == 1, assertError pos (-1), pos 2 == 2, assertError pos (-2)]
runTests = all (== True) tests
[我的解决方案]
这就是我根据@hammar 的评论最终得出的结论。
instance Eq ErrorCall where
x == y = (show x) == (show y)
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)
assertError ex f =
TestCase $ assertException (ErrorCall ex) $ evaluate f
tests = TestList [ (pos 0) ~?= 0
, (pos 1) ~?= 1
, assertError "Invalid Input" (pos (-1))
]
main = runTestTT tests
OP 的解决方案定义assertException
,但看起来像Test.HUnit.Tools.assertRaises
from testpack这里也可以使用。
我添加了msg
论证assertError
匹配如何assertRaises
有效,并且包含选择性导入,这样像我这样的菜鸟就可以了解常用的东西是从哪里导入的。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)