测试返回Maybe Monad的函数

时间:2016-01-16 12:16:02

标签: haskell testing monads assertions hspec

说我有一个功能:

safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead xs = Just $ head xs

测试:

describe "Example.safeHead" $ do
  it "returns the head" $ do
    safeHead [1,2,3] `shouldBe` Just 1

  it "returns Nothing for an empty list" $
    safeHead [] `shouldBe` Nothing
然而,

这会产生:

No instance for (Eq a0) arising from a use of ‘shouldBe’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance (Eq a, Eq b) => Eq (Either a b)
    -- Defined in ‘Data.Either’
  instance forall (k :: BOX) (s :: k). Eq (Data.Proxy.Proxy s)
    -- Defined in ‘Data.Proxy’
  instance (GHC.Arr.Ix i, Eq e) => Eq (GHC.Arr.Array i e)
    -- Defined in ‘GHC.Arr’
  ...plus 88 others
In the second argument of ‘($)’, namely
  ‘safeHead [] `shouldBe` Nothing’
In a stmt of a 'do' block:
  it "returns Nothing for an empty list"
  $ safeHead [] `shouldBe` Nothing
In the second argument of ‘($)’, namely
  ‘do { it "returns the head"
        $ do { safeHead [...] `shouldBe` Just 1 };
        it "returns Nothing for an empty list"
        $ safeHead [] `shouldBe` Nothing }’

为什么呢?我该如何解决?

3 个答案:

答案 0 :(得分:4)

正如user2407038评论的那样,编译器并不知道如何实例化a。他提出的修复可能是最好的 - 您应该明确指定a的类型。

但为了完整起见,我还要注意,还有其他解决方案,extended default rules

{-# LANGUAGE ExtendedDefaultRules #-}

describe "Example.safeHead" $ do
  it "returns the head" $ do
    safeHead [1,2,3] `shouldBe` Just 1

  it "returns Nothing for an empty list" $
    safeHead [] `shouldBe` Nothing

扩展程序会修改the standard defaulting rules以包含更多案例,例如Eq类型类。

添加:经过一番思考后,我重新考虑了一下我的回答。多态函数的单元测试结果不应该依赖于实例化类型变量的特定方式。所以可能扩展的默认规则是测试中的正确的东西?我从来没有把它用作真正的代码,所以我无法肯定地说,但绝对值得考虑。

答案 1 :(得分:2)

shouldBe                :: (Eq a, Show a) => a -> a -> Expectation
safeHead                ::         [a] ->    Maybe a
[]                      ::         [a]
safeHead []             ::                   Maybe a
Nothing                 ::                   Maybe a
shouldBe (safeHead [])  :: (Eq a, Show a) => Maybe a -> Expectation

shouldBe (safeHead []) Nothing ::                       Expectation -- but what's `a`?

如您所见,a完全不明确。它可以是具有ShowEq个实例的任何类型。这也是错误消息的一部分:

No instance for (Eq a0) arising from a use of ‘shouldBe’
The type variable ‘a0’ is ambiguous

所以选择一个:

it "returns Nothing for an empty list" $
    safeHead [] `shouldBe` (Nothing :: Maybe ())

当您使用它时,请使用QuickCheck验证safeHead的工作方式是否为head

it "returns Just (head xs) for a non-empty list" $ property $ \(NonEmpty xs) ->
    safeHead xs `shouldBe` (Just (head xs) :: Maybe Integer)

答案 2 :(得分:0)

此代码测试可能返回“ Just”值的Maybe Monad:

     import Test.Tasty
     import Test.Tasty.HUnit
     import Data.List         

     main = defaultMain tests

     tests = testGroup "Tests uncons form Data.List"

     [testCase "Show uncons [1,2,3,4] = (1, [2,3,4])" $
     Just (1,[2,3,4]) @=? (uncons [1,2,3,4])]