Is it possible to exclude some fields from assertJ usingFieldByFieldElementComparator?
Asked Answered
G

2

11

How to achieve the below:

List<Data> streams = new ArrayList<>();
assertThat(streams).usingFieldByFieldElementComparatorIgnoringGivenFields("createdOn").containsOnly(data1, data2);
Glaucescent answered 23/3, 2018 at 10:42 Comment(0)
T
25

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);
Thermoelectrometer answered 23/3, 2018 at 10:51 Comment(4)
Is it possible to relax comparison of Date() by 1000ms (isCloseTo operation) in the above code format you have suggested ?Glaucescent
@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));Thermoelectrometer
I had trouble with it for whatever odd reason, but using usingElementComparatorOnFields("foo", "bar") was quite useful.Cathepsin
usingElementComparatorIgnoringFields is deprecated, now you should use usingRecursiveFieldByFieldElementComparatorIgnoringFields instead.Schaub
G
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.

Geriatrics answered 30/12, 2022 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.