2017-07-22 31 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中打開,在其他地方默認關閉。 –

相關問題