1

我遇到了一个奇怪的HUnit行为。如果测试中存在条件,则不允许编译Nothing == Nothing测试用例。这是我重现此行为的代码:

module TestTest where 

import Control.Exception
import Control.Monad
import Test.HUnit
import Test.AssertError

testTests = test [ 
    "test A01"  ~: "x == x" ~: True ~=? Nothing == Nothing,
    "test _"    ~: "empty test" ~: True ~=? True
    ]

runTests :: IO Counts
runTests = do
    runTestTT testTests

尝试使用此内容加载文件会ghci返回以下错误:

[2 of 2] Compiling TestTest         ( Test/TestTest.hs, interpreted )

Test/TestTest.hs:9:49:
    No instance for (Eq a0) arising from a use of ‘==’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance Eq Counts -- Defined in ‘Test.HUnit.Base’
      instance Eq Node -- Defined in ‘Test.HUnit.Base’
      instance Eq State -- Defined in ‘Test.HUnit.Base’
      ...plus 53 others
    In the second argument of ‘(~=?)’, namely ‘Nothing == Nothing’
    In the second argument of ‘(~:)’, namely
      ‘True ~=? Nothing == Nothing’
    In the second argument of ‘(~:)’, namely
      ‘"x == x" ~: True ~=? Nothing == Nothing’
Failed, modules loaded: Test.AssertError.

请注意,Just 2 == Just 2同一测试用例中的条件可以正常工作。如果我输入Nothing == Nothingghci它会True按预期返回。

任何想法为什么HUnit会这样?这是错误还是预期行为?

4

1 回答 1

3

问题是您指定了两个Nothings,因此这些都没有暗示a将是什么类型。当然,你可以推理,因为Nothing这并不重要。(==)但是 Haskell 并没有这样推理:它对“我应该指向什么函数?”感兴趣。

您可以通过明确类型来解决问题。例如:

testTests = test [ 
  "test A01"  ~: "x == x" ~: True ~=? (Nothing :: Maybe Int) == Nothing,
  "test _"    ~: "empty test" ~: True ~=? True
  ]
于 2017-07-22T13:06:00.860 回答