【问题标题】:Is there a Kotest assertion to test if a list contains some element with a given property?是否有 Kotest 断言来测试列表是否包含具有给定属性的某些元素?
【发布时间】:2021-12-01 17:57:28
【问题描述】:

我有两个对象有一些共同点,我想比较一下

data class Pet(val colour: String, val owner: Human, val legCount: Int)
data class Car(val colour: String, val owner: Human, val isElectric: Boolean)

我想断言List<Car> 中的某些元素包含与给定Pet 具有相同颜色和所有者的元素。

这是一个假代码示例来说明我正在尝试做的事情:

cars.containsElementSatisfying { car ->
    pet.colour shouldBe car.colour
    pet.owner shouldBe car.owner
}

我如何使用 kotest 做到这一点?我可以使用 assertJ 的 anySatisfy 断言来完成所需的功能。

【问题讨论】:

    标签: unit-testing kotlin kotest


    【解决方案1】:

    我找到了解决方案。 "Inspectors" kotest 库包含许多类似于assertJ 的anySatisfy 断言的函数,特别是集合函数forAtLeastOneforAtLeast(k)

    以下是示例用法:

    cars.forAtLeastOne { car -> 
        pet.colour shouldBe car.colour
        pet.owner shouldBe car.owner
    }
    

    https://kotest.io/docs/assertions/inspectors.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多