我希望能够确保函数在接收到无效值时会引发错误。例如,假设我有一个函数 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