https://kotlinlang.org logo
#kotest
Title
# kotest
s

Shervin

01/16/2023, 12:58 PM
Hey everyone! do we have an 'ignoring' assertion which works on Collections? I want to compare two lists, ignoring the id of their content. Imagine:
data class Person (val id: String, val name: String)
I expect sth like the following:
listOf(Person("0", "Tom")).shouldBeEqualToIgnoringFields(listOf(Person("1", "Tom")), Person::id)
do we have this? 🙏
e

Emil Kantis

01/16/2023, 12:59 PM
Copy code
val tom = Person("1", "Tom")
val persons = listOf(Person("0", "Tom"))

persons.forOne {
  it.shouldBeEqualToIgnoringFields(tom, Person::id)
}
s

Shervin

01/16/2023, 1:10 PM
hm, yeah it works, but what if I want to assert List A is equal to List B ? ignoring a field on the Item
I'm looking for sth like:
Copy code
shouldContainAllIgnoringFields
that would ideal for me. one liner assertion for comparing Collections while ignoring a field.
Hey @sam! Is there a reason that we don't have this? or is it a possible assertion that we can have?
s

sam

01/16/2023, 1:22 PM
Yeah can add it, would welcome a PR.
s

Shervin

01/16/2023, 1:36 PM
I will create a PR for this shortly
d

Davio

01/16/2023, 2:11 PM
How about some zipped assertion with a custom matcher like AssertJ has?
s

sam

01/16/2023, 2:11 PM
link ?
Could be quite a flexible approach
s

sam

01/16/2023, 2:14 PM
could you do this with just
listA.zip(listB).forAll { (a,b) -> }
e

Emil Kantis

01/16/2023, 2:16 PM
s

Shervin

01/16/2023, 2:16 PM
zipSatisfy
compares 1 to 1, right? where as in Contains items might not be in the exact order
s

sam

01/16/2023, 2:17 PM
I think zipSatisfy is just zipping two lists together and then comparing each pair of elements in turn against some assertions. So that's just regular zip plus a Kotest inspector ( I think !)
d

Davio

01/16/2023, 2:20 PM
Yeah my assumption was that the lists have the elements in the same order
s

Shervin

01/16/2023, 2:22 PM
that can also be of use, but in my case I want to be flexible with the orders of the items. I don't want to rewrite the test every-time I change the order returned in the api 😄
Thanks for the suggestion! didn't know zipSatisfy exist!
Hey @sam! I finally found some time to work on this, I have a question about principles that I need to follow if you could clarify please: I've added:
Copy code
fun <T : Any> Iterable<T>.shouldContainAllIgnoringFields(...)
to support comparing Iterables ignoring field(s). Now my question is may I re-use our current
Copy code
beEqualToIgnoringFields
that we have, to compare the items in the list? In other words, can a matcher re-use another matcher? 🙏
d

Davio

02/08/2023, 7:49 AM
I wouldn't see why not, I think this makes more sense than writing manual assertions each time
s

Shervin

02/08/2023, 10:29 AM
Thanks @Davio I thought so
318 Views