関数が無効な値を受け取ったときにエラーをスローするようにしたいと考えています。たとえば、正の数のみを返す関数 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