haskell - 如何在Haskell中使用测试包中的assertRaises?

标签 haskell exception

我正在学习 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))'

出了什么问题?

最佳答案

assertRaises 期望其第三个参数是 IO 操作(类型为 IO a),但 foo 的返回类型是数字(类型为 (Num a, Ord a) => a),不是 IO 操作。

尝试将 (foo 4) 替换为 (evaluate (foo 4))

关于haskell - 如何在Haskell中使用测试包中的assertRaises?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9597700/

相关文章:

Django:create_user 抛出什么样的异常?

asp.net - Application_Start 中出现间歇性异常 - 如何取消启动应用程序?

haskell - 打印带有变量名称的 AST

haskell - `Alternative` 中的模式匹配

haskell - yst和hakyll静态网站生成器的比较优缺点是什么?

c++ - 如何更改我的错误处理方法

haskell - 检查 Haskell 列表中是否存在元素

c# - iteratee I/O 在非函数式语言中有意义吗?

C# - 抛出异常时无限循环?

java - JOptionPane YES_NO_OPTION 不理解异常