1

In unit tests I usually use something like

assertThat(someObject).isEqualTo(someOtherObject);

to make sure these two objects have identical content. But what to do in case objects have identical content except certain fields?

Normally it would be like that:

assertThat(someObject.getFirstField()).isNotEqualTo(someOtherObject.getFirstField());
assertThat(someObject.getLastField()).isNotEqualTo(someOtherObject.getLastFieldd());
// and then gazilion fields that should be equal
assertThat(someObject.getNthField()).isEqualTo(someOtherObject.getNthField());
// ...

For obvious reasons, it is very unwieldy for bigger classes with a lot of fields. Is there way to specify that you expect certain fields to be not equal, but rest equal?

Both someObject and someOtherObject are same class that is Lomboked, so equals() is automatically handled.

Mader Levap
  • 455
  • 5
  • 15
  • You could have the objects implement a `looksLike(SomeOBject other)` method that has the right criteria for "similarity". That is, if you only have one type of similarity in mind, implying a definite set of fields. Otherwise it gets more complicated... – Mena Mar 15 '18 at 14:17
  • are all of those fields of the same type? – Stultuske Mar 15 '18 at 14:18
  • Possible duplicate of [How do I assert equality on two classes without an equals method?](https://stackoverflow.com/questions/12147297/how-do-i-assert-equality-on-two-classes-without-an-equals-method) – acontell Mar 15 '18 at 14:30

1 Answers1

3

If you are open to using assertJ then there is a very simple solution to your problem. Use

assertThat(someObject).isEqualToIgnoringGivenFields(someObjectOther, "firstField", "lastField")

Bear in mind that this uses reflection internally and failures can happen if you change the name of your fields inside the class which you want to ignore.

More on this Field by field comparisons

Sneh
  • 3,527
  • 2
  • 19
  • 37
  • 1
    by doing this, you are changing the functionality of the comparison. saying "this may not be equal to", is not the same as "ignore this when you are comparing" – Stultuske Mar 15 '18 at 14:28
  • 1
    That's true! I wonder if we can add the notEqualTo asserts in the test after the isEqualToIgnoringGivenFields. – Sneh Mar 15 '18 at 14:30
  • 1
    This is exactly what I needed. In combo with notEqualTo it should ensure that there IS some change in at least one of ignored fields. – Mader Levap Mar 15 '18 at 16:37
  • Glad I could help :D – Sneh Mar 15 '18 at 16:50