Assert that every object property matches given predicate in kotlin test

Viewed 768

I have a collection of objects:

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

I would like to test that each and every item matches given predicate on field.

Is there any assertion in kotlintest assertions that will allow me to do so?

Something like:

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

I ended up submitting PR in kotest that will provide such functionality:

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"
   )
}

You can simply use the all function; i.e.:

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