Search code examples
androidandroid-testingassertjgoogle-truth

Truth ignore field


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.


Solution

  • 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").)