Exception 如何在Haskell中使用testpack中的assertRaises?
我正在学习Haskell,我想做TDD。 我试图测试函数是否引发预期的异常。 我正在使用HUnit和 testpack提供了assertRaises函数,但我无法编译代码:( 以下是我的源代码:Exception 如何在Haskell中使用testpack中的assertRaises?,exception,haskell,exception-handling,Exception,Haskell,Exception Handling,我正在学习Haskell,我想做TDD。 我试图测试函数是否引发预期的异常。 我正在使用HUnit和 testpack提供了assertRaises函数,但我无法编译代码:( 以下是我的源代码: module Main where import Test.HUnit import Test.HUnit.Tools import Control.Exception foo n | n > 2 = throw ( IndexOutOfBounds ( "Index out of boun
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))'
怎么了?
assertRaises
希望它的第三个参数是IO操作(类型为IO a
),但是foo
的返回类型是一个数字(类型为(Num a,Ord a)=>a
),而不是IO操作
试着用
(evaluate(foo 4))
替换(foo 4)
,由于懒惰,我认为return
在这里不起作用。evaluate
应该可以做这项工作。@hammar我太马虎了。谢谢。