在遇到undefined
時,在Haskell中編寫一個表達式失敗的單元測試有點棘手。我試了下HSpec:單元測試在Haskell中延遲表達式中評估的undefined
module Main where
import Test.Hspec
import Control.Exception (evaluate)
main :: IO()
main = hspec $ do
describe "Test" $ do
it "test case" $ do
evaluate (take 1 $ map (+1) [undefined, 2, 3]) `shouldThrow` anyException
無濟於事。它報告我did not get expected exception: SomeException
如果我評價REPL同樣的表情,我會得到:
[*** Exception: Prelude.undefined
CallStack (from HasCallStack):
error, called at libraries\base\GHC\Err.hs:79:14 in base:GHC.Err
undefined, called at <interactive>:2:20 in interactive:Ghci1
這個答案很好,但是當你說[評估]沒有評估爲WHNF時[我的文檔明確聲明它評估它的參數爲WHNF],我很困惑(https://hackage.haskell.org /package/base-4.9.0.0/docs/Control-Exception.html#v:evaluate)。 –
@AlexisKing我的立場正確!無論如何,WNHF還不夠,所以你需要'NFData'。 – Alec
所以,實際上,測試通過,因爲它產生一個單一的未定義元素的列表?爲什麼不應用(+1)函數? –