【问题标题】:Write nested assertions with Hspec使用 Hspec 编写嵌套断言
【发布时间】:2021-05-02 20:29:48
【问题描述】:

我正在努力用 HSpec 实现一个看似简单的测试问题:我想测试一个函数

myFunc :: (Exception e) a -> Either e MyRecord

在一个测试用例中,我想首先断言返回值是Right 值,然后打开该值以断言其内容。如果没有繁琐的 case 表达式,我还没有想出一种方法来做到这一点。是否存在同时允许模式匹配的断言运算符?

我正在寻找的是以下几行(伪 Haskell):

describe "myFunc" $ do
    it "should return funky stuff" $ do
      let result = myFunc <testArgument>
      result `shouldBe` (Right testRecord)
      testRecord `shouldBe` <expectedRecord>

这只是为了说明这个想法,当然,RHS 上的模式匹配不起作用。

【问题讨论】:

  • 为什么result `shouldBe` (Right testRecord) 还不够? shouldBe 函数有一个Eq 约束,当ab 都是Eq 实例时,Either 只是一个Eq 实例。因此,只有当Right 的内容等于预期结果时,该断言才应该通过。
  • @MarkSeemann Left 类型的Either 没有Eq 实例不是问题所在吗?

标签: haskell either hspec


【解决方案1】:

shouldSatisfy 使用自定义函数,例如:result `shouldSatisfy` either (const False) (&lt;expectedRecord&gt; ==)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2018-03-08
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多