Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Kotest assertion to test if a list contains some element with a given property?

I have two objects that have some features in common that I would like to compare

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

I would like to assert that some element in a List<Car> contains an element with the same colour and owner as a given Pet.

Here's a fake code example to illustrate what I'm trying to do:

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

How might I do this using kotest? I can accomplish the desired functionality using assertJ's anySatisfy assertion.

like image 486
mooglin Avatar asked Dec 09 '25 04:12

mooglin


1 Answers

I found the solution. The "Inspectors" kotest library contains a number of functions similar to assertJ's anySatisfy assertion, in particular the collection functions forAtLeastOne and forAtLeast(k)

Here's example usage:

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

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

like image 190
mooglin Avatar answered Dec 12 '25 00:12

mooglin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!