我希望能够确保当函数接收到无效值时,它会抛出一个错误。例如,假设我有一个函数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
error
语句会抛出一个ErrorCall
异常。请参考我在这里的回答,了解如何使用HUnit测试异常。 - hammarall (== True)
等于all id
等于and
。) - huon