https://kotlinlang.org logo
#strikt
Title
# strikt
c

christophsturm

02/01/2021, 12:17 PM
lets say i have a list of objects and assert on it. if i know all the field values its easy:
Copy code
import strikt.api.expectThat
import strikt.assertions.containsExactly

data class Person(val name: String, val age: Int)

expectThat(listOf(Person("james", 28), Person("jimmy", 28))).containsExactly(
    Person("james", 28), Person("jimmy", 28)
)
but what if there is a third field that is random, and that i can’t assert on, what would be the best way to write that in strikt?
Copy code
data class Person(val name: String, val age: Int, val weight:Double=Random.nextDouble())
i want all the elements and the order but not assert on weight.
I think what i want is
Copy code
expectThat(listOf(Person("james", 28), Person("jimmy", 28))).containsExactly(
    obj{ get {name}.isEqualTo("james"), get{age}.isEqualTo(28)}, obj{ get {name}.isEqualTo("jim"), get{age}.isEqualTo(28)}
)
i mean what i really want is
Copy code
expectThat(listOf(Person("james", 28), Person("jimmy", 28))).containsExactly(
    listOf(Person("james", 28), Person("jimmy", 28))
, ignore=Person::weight)
r

robfletcher

02/01/2021, 2:59 PM
Part of me wonders why such a property would be part of the
equals
implementation on the class if it really doesn’t represent logical equality. i.e. is it the test that needs to change, or is the difficulty in implementing the test telling you something about the design?
I was wondering if Kotlin data classes ignore
@Transient
fields in their
equals
implementation but apparently not
c

christophsturm

02/01/2021, 3:25 PM
thinking of it more thats actually a good point. I thought that i don’t want to assert on all the fields because the data class contains a lot of values and I don’t want to assert on all of them in one test. but I can just map to one unique field in the tests that test the order, and test the other fields separately in tests with just one result.
r

robfletcher

02/01/2021, 3:32 PM
I’d like to implement
isOrdered()
and
isOrderedBy(Comparator)
assertions
c

christophsturm

02/01/2021, 3:37 PM
but in my case its ordered by its position in the file 🙂
Copy code
expectThat(listOf(Person("james", 28), Person("jimmy", 28))).map{it.copy(weight=>null)}. containsExactly(
    listOf(Person("james", 28), Person("jimmy", 28)))
this could work btw, but you are right its just not a great test
r

robfletcher

02/02/2021, 3:36 PM
I forgot Strikt already has
fun <T : Collection<E>, E> Builder<T>.isSorted(comparator: Comparator<E>)
. I’m adding
fun <T : Collection<E>, E : Comparable<E>> Builder<T>.isSorted()
now
34 Views