Как использовать assertRaises из testpack в Haskell? - PullRequest
2 голосов
/ 07 марта 2012

Я изучаю 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))'

Что не так?

1 Ответ

3 голосов
/ 07 марта 2012

assertRaises ожидает, что его третий аргумент будет действием ввода-вывода (с типом IO a), но тип возвращаемого значения foo является числом (с типом (Num a, Ord a) => a), а не действием ввода-вывода.

Попробуйте заменить (foo 4) на (evaluate (foo 4)).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...