I have a class Something:
public class Something {
public String a;
public String b;
}
Suppose I can't write equals or compare method in class Something.
My test:
Set<Something> aSet;
Set<Something> otherSet;
assertEquals(aSet, otherSet);//Fails because it only compares references of elements and does not perform a deep comparision field by field
Is there any way to assert if both sets are equals comparing elements field by field (without writing equals method in Something class)?
Give a try to AssertJ, it provides a way to compare element field by field recursively, example:
// the Dude class does not override equals
Dude jon = new Dude("Jon", 1.2);
Dude sam = new Dude("Sam", 1.3);
jon.friend = sam;
sam.friend = jon;
Dude jonClone = new Dude("Jon", 1.2);
Dude samClone = new Dude("Sam", 1.3);
jonClone.friend = samClone;
samClone.friend = jonClone;
assertThat(asList(jon, sam)).usingRecursiveFieldByFieldElementComparator()
.contains(jonClone, samClone);
Another possibility is to compare collections using a specific element comparator so SomethingComparator
in your case, this requires a bit more work than the first option but you have full control of the comparison.
Hope it helps!