我正在学习Haskell,我想做TDD。 我试图测试函数是否引发预期的异常。 我正在使用HUnit和testpack。
testpack提供了一个assertRaises函数,但我无法编译我的代码:(
这是我的源代码:
module Main where
import Test.HUnit
import Test.HUnit.Tools
import Control.Exception
foo n | n > 2 = throw ( IndexOutOfBounds ( "Index out of bounds : " ++ ( show n ) ) )
foo n | otherwise = n
testException = TestCase( assertRaises "throw exception" ( IndexOutOfBounds "Index out of bounds : 4" ) ( foo 4 ) )
main = runTestTT ( TestList [ testException ] )
当我用ghc编译它时,我收到以下错误消息:
test_exceptions.hs:10:107:
No instance for (Ord (IO a0))
arising from a use of `foo'
Possible fix: add an instance declaration for (Ord (IO a0))
In the third argument of `assertRaises', namely `(foo 4)'
In the first argument of `TestCase', namely
`(assertRaises
"throw exception"
(IndexOutOfBounds "Index out of bounds : 4")
(foo 4))'
In the expression:
TestCase
(assertRaises
"throw exception"
(IndexOutOfBounds "Index out of bounds : 4")
(foo 4))
test_exceptions.hs:10:111:
No instance for (Num (IO a0))
arising from the literal `4'
Possible fix: add an instance declaration for (Num (IO a0))
In the first argument of `foo', namely `4'
In the third argument of `assertRaises', namely `(foo 4)'
In the first argument of `TestCase', namely
`(assertRaises
"throw exception"
(IndexOutOfBounds "Index out of bounds : 4")
(foo 4))'
怎么了?
答案 0 :(得分:3)
assertRaises
期望其第三个参数是IO操作(类型为IO a
),但foo
的返回类型是一个数字(类型为(Num a, Ord a) => a
),不是IO行动。
尝试将(foo 4)
替换为(evaluate (foo 4))
。