简体   繁体   English

Haskell HUnit Function 测试

[英]Haskell HUnit Function Testing

I'm trying to set up a series of tests for a simple tic tac toe program I've written in Haskell and I'm unable to get past my first test due to a strange error being thrown reading:我正在尝试为我在 Haskell 中编写的一个简单的井字游戏程序设置一系列测试,但由于一个奇怪的错误被抛出读取,我无法通过我的第一个测试:

Tests.hs:11:61: error:
    * Couldn't match expected type `Int' with actual type `IO Int'
    * In the third argument of `assertEqual', namely
        `(test_user_value x)'
      In the first argument of `TestCase', namely
        `(assertEqual "for (test_user_value 3)," f (test_user_value x))'
      In the expression:
        TestCase
          (assertEqual "for (test_user_value 3)," f (test_user_value x))
   |
11 | test1 = TestCase (assertEqual "for (test_user_value 3)," f (test_user_value x))
   |                                                             ^^^^^^^^^^^^^^^^^
Failed, one module loaded.

The value 'x' is an int but Haskell is reading it as 'IO Int' which is wrong, as I've specified "x:: Int".值“x”是一个 int,但 Haskell 将其读取为“IO Int”,这是错误的,因为我指定了“x:: Int”。 The function being tested has already been specified as "test_user_value:: Int -> IO Int" so I'm unsure why it is interpreting the variable incorrectly.正在测试的 function 已被指定为“test_user_value:: Int -> IO Int”,所以我不确定它为什么会错误地解释变量。 Any suggestions would be appreciated.任何建议,将不胜感激。

It's not actually complaining about x , it's complaining about the expression test_user_value x - note that it is this expression that is underlined in the error message.它实际上并不是在抱怨x ,而是在抱怨表达式test_user_value x - 请注意,错误消息中带有下划线的是这个表达式。

Since, as you have indicated, test_user_value:: Int -> IO Int and x:: Int , it follows that test_user_value x:: IO Int - and that's exactly what the compiler tells you shouldn't be there.因为,正如您所指出的, test_user_value:: Int -> IO Intx:: Int ,因此test_user_value x:: IO Int - 这正是编译器告诉你的不应该在那里。 It's expecting an Int , but you gave it IO Int .它期待一个Int ,但你给了它IO Int

You can get an Int out of it though.不过,您可以从中获得Int To do that, I think the do notation would be the clearest:为此,我认为do表示法是最清晰的:

test1 = TestCase $ do
    v <- test_user_value x
    assertEqual "for (test_user_value 3)," f v

Or you could write it a bit shorter using the =<< operator:或者您可以使用=<<运算符将其写得更短一些:

test1 = TestCase (assertEqual "for (test_user_value 3)," f =<< test_user_value x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM