javaassertionsassertj

Is it possible to exclude some fields from assertJ usingFieldByFieldElementComparator?


How to achieve the below:

List<Data> streams = new ArrayList<>();
assertThat(streams).usingFieldByFieldElementComparatorIgnoringGivenFields("createdOn").containsOnly(data1, data2);

Solution

  • Use ListAssert.usingElementComparatorIgnoringFields(String... fields) that does the same thing as ListAssert.usingFieldByFieldElementComparator() but by allowing to ignore some fields/properties :

    Use field/property by field/property comparison on all fields/properties except the given ones

    So you could write :

    List<Data> streams = new ArrayList<>();
    //...
    Assertions.assertThat(streams)
              .usingElementComparatorIgnoringFields("createdOn")
              .containsOnly(data1, data2);