断言每个对象 属性 与 kotlin 测试中的给定谓词匹配

Assert that every object property matches given predicate in kotlin test

我有一个对象集合:

data class WeatherForecast(
    val city: String,
    val forecast: String
    // ...
)

我想测试每个项目是否与字段上给定的谓词相匹配。

kotlintest assertions 中是否有任何断言允许我这样做?

类似于:

 forecasts.eachItemshouldMatch{ it.forecast == "SUNNY" }

您可以简单地使用all功能;即:

forecasts.all { it.forecast == "SUNNY" }

我最终在 kotest 中提交了将提供此类功能的 PR:

https://github.com/kotest/kotest/pull/2692

infix fun <T> Collection<T>.allShouldMatch(p: (T) -> Boolean) = this should match(p)
fun <T> match(p: (T) -> Boolean) = object : Matcher<Collection<T>> {
   override fun test(value: Collection<T>) = MatcherResult(
      value.all { p(it) },
      "Collection should have all elements that match the predicate $p",
      "Collection should not contain elements that match the predicate $p"
   )
}

使用检查员怎么样。

list.forAll {
  it.forecast shouldBe "SUNNY"
}

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