2017-07-22 41 views
1

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

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工作正常。如果我在ghci中输入Nothing == Nothing,则按预期返回True

任何想法为什么HUnit可能会这样?这是一个错误还是预期的行为?

+0

您应该指定'Maybe a'的类型。 –

回答

3

问题是您指定了两个Nothing s,并且这些都没有提示a的类型。当然,你可以推断,对于Nothing这并不重要。但是Haskell并没有这样推理:它对“我应该指出什么(==)函数”感兴趣?“。

您可以通过使类型显式来解决问题。例如:

testTests = test [ 
    "test A01" ~: "x == x" ~: True ~=? (Nothing :: Maybe Int) == Nothing, 
    "test _" ~: "empty test" ~: True ~=? True 
    ]
+0

为什么在'ghci'中运行'Nothing == Nothing'会返回'True'而没有明确指定整个类型? – altern

+0

@altern:因为'ghci'推迟了接地。仅仅因为它不能立即做到这一点。 'ghc'将解释所有文件,然后解释这些。 –

+7

@altern由于[扩展默认](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#extended-default-rules),它在不明确类型的情况下选择单形类型更经常地,并且默认在ghci中打开,在其他地方默认关闭。 –