1

我有一个对象集合:

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

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

是否有任何断言kotlintest assertions可以让我这样做?

就像是:

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

3 回答 3

2

使用检查员怎么样。

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

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

于 2021-12-01T02:37:51.280 回答
0

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

forecasts.all { it.forecast == "SUNNY" }
于 2021-11-26T22:38:47.203 回答
0

我最终在 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"
   )
}
于 2021-11-29T11:10:25.760 回答