1

I am looking for Guava Truth equivalent of AssertJ usingElementComparatorIgnoringFields to ignore some field.

Exemple:

    data class CalendarEntity(
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0,
    var name: String
) 
Truth.assertThat(currentCalendars).containsExactlyElementsIn(expectedCalendars) // Here I want to ignore the id field 

Thanks for your help.

Louis
  • 364
  • 3
  • 11

1 Answers1

2

For Truth, we decided not to provide reflection-based APIs, so there's no built-in equivalent.

Our general approach to custom comparisons is Fuzzy Truth. In your case, that would look something like this (Java, untested):

Correspondence<CalendarEntity, CalendarEntity> ignoreId =
    Correspondence.from(
        (a, b) -> a.name.equals(b.name),
        "fields other than ID");
assertThat(currentCalendars).usingCorrespondence(ignoreId).containsExactlyElementsIn(expectedCalendars);

If you anticipate wanting this a lot (and you want to stick with Truth rather than AssertJ), then you could generalize the ignoreId code to work with arbitrary field names.

(Also: In this specific example, your CalendarEntity has only one field that you do want to compare. In that case, you can construct the Correspondence in a slightly simpler way: Correspondence.transforming(CalendarEntity::name, "name").)

Chris Povirk
  • 3,738
  • 3
  • 29
  • 47