9

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

2 回答 2

4

OP 的解决方案定义了,但从testpackassertException看起来也可以在这里使用。Test.HUnit.Tools.assertRaises

我添加了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
于 2013-02-10T19:49:41.137 回答
0

在 Haskell 中有几种处理错误的方法。这是一个概述:http ://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors

[编辑]

第一个例子展示了如何捕捉错误,例如

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

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

也就是说,这种错误处理更适合IO一些东西,在像你这样的纯代码中,Maybe,Either 或类似的东西通常是更好的选择。它可以简单到...

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

...如果您不需要错误类型。

于 2012-11-12T19:37:43.807 回答