Search code examples
unit-testingkotlinkotest

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.


Solution

  • 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