0

我有一个Entity定义如下的数据类:

data Entity = Entity { id :: String, name :: String }

和一个返回的函数IO Entity

newPersistentEntity :: String -> IO Entity

我想为此编写一个HSpec测试:

spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" `shouldReturn` Entity {id = <any string>, name = "myName"}

问题是 id 是数据库生成的 UUID。我想断言这id是一个使测试通过的字符串。

我怎样才能做到这一点?

4

3 回答 3

2

您可以创建记录,然后使用它的id值来创建您要比较的记录吗?就像是:

new <- newPersistentEntity "myName"
new `shouldBe` Entity { id = (id new), name = "myName" }

(注意:没有足够的信息来测试此代码,将其视为伪代码)。

作为旁注,您的代码看起来不像普通的持久代码,所以我假设您使用的是不同的库。

于 2017-12-06T18:24:03.477 回答
2

idof anEntity不能不是 a ,String因为静态类型。但是您可能确实想强制其评估以确保它不是底部。

spec :: Spec
spec = describe "newPersistentEntity function" $
    it "returns a new Entity with a generated id and the specified name" $ do
        x <- newPersistentEntity "myName"
        pure $! id x  -- Force evaluation of the `id` field to ensure that
                      -- the database actually did return a string here
        name x `shouldBe` "myName"
于 2017-12-06T19:44:52.430 回答
2

实际上,我自己以不同的方式解决了这个问题,我将在此处显示上下文。您可能不应该使用它,因为接受的答案更容易理解且不那么冗长。

spec :: Spec
spec = describe "newPersistentEntity function" $
       it "returns a new Entity with a generated id and the specified name" $
       newPersistentEntity "myName" >>= (`shouldSatisfy` (\case
           Entity {id = _, name = "myName"} -> True
           _ -> False))

但要使其正常工作,您还需要应用 lamda case 语言扩展:

{-# LANGUAGE LambdaCase #-}
于 2017-12-07T05:55:13.523 回答