10

How to achieve the below:

List<Data> streams = new ArrayList<>();
assertThat(streams).usingFieldByFieldElementComparatorIgnoringGivenFields("createdOn").containsOnly(data1, data2);
Vel Ganesh
  • 537
  • 3
  • 12
  • 32

2 Answers2

23

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);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Is it possible to relax comparison of Date() by 1000ms (isCloseTo operation) in the above code format you have suggested ? – Vel Ganesh Mar 28 '18 at 09:32
  • @Vel Ganesh You are welcome. I don't think that it be possible with this AssertJ comparator. For such requirements, I generally exclude it from the AssertJ comparison and I perform it with a JUnit assertion such as: `Assert.assertTrue(date.after(lowerLimitDate) && date.before(upperLimitDate));` – davidxxx Mar 29 '18 at 18:24
  • I had trouble with it for whatever odd reason, but using `usingElementComparatorOnFields("foo", "bar")` was quite useful. – Philippe Dec 12 '19 at 17:28
  • `usingElementComparatorIgnoringFields` is deprecated, now you should use `usingRecursiveFieldByFieldElementComparatorIgnoringFields` instead. – S.H. Jan 25 '23 at 09:22
0

If you (1) have control of the source code of data and (2) are using Lombok annotations then you can use the @EqualsAndHashCode.Exclude against the createdOn field e.g.

import lombok.*;

@Data
public class Data {

    @EqualsAndHashCode.Exclude   // will not include this field in the generated equals and hashCode methods.
    private Date createdOn;

    ...
}

This really simplifies the testing:

assertThat(streams).containsOnly(data1, data2);

NOTE: if you do use equals() methods on the Data object as part of the src/main/java classes, you will need to ensure the values of the other fields are enough to make the object unique so that equals() works properly when using @EqualsAndHashCode.Exclude.

bobmarksie
  • 3,282
  • 1
  • 41
  • 54