Given the following (quick and missing) code:
class Pair{
int x;
int y;
}
List l1 = Arrays.asList(new Match(1,2), new Match(1,3), new Match(2,3));
List l2 = Arrays.asList(new Match(1,2), new Match(1,3), new Match(2,3));
How can I compare the content of the lists? Everything I used so far checked if the objects themselves were equal and not the objects value:
assertThat(l1).isEqualTo(l2);
assertThat(l1).containsAll(l2);
assertThat(l1).containsExactly(values);
assertThat(l1).containsExactlyElementsOf(iterable);
Must I implement equals() method for Match class?
May this be the correct way?
for (int i = 0; i < l1.size(); i++){
assertThat(l1.get(i)).usingRecursiveComparison().isEqualTol2.get(i));
}
Give a try to usingRecursiveFieldByFieldElementComparator(recursiveConfiguration), it enables recursive comparison to all iterable assertions.
Ex:
public class Person {
String name;
boolean hasPhd;
}
public class Doctor {
String name;
boolean hasPhd;
}
Doctor drSheldon = new Doctor("Sheldon Cooper", true);
Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
Doctor drRaj = new Doctor("Raj Koothrappali", true);
Person sheldon = new Person("Sheldon Cooper", false);
Person leonard = new Person("Leonard Hofstadter", false);
Person raj = new Person("Raj Koothrappali", false);
Person howard = new Person("Howard Wolowitz", false);
List<Doctor> doctors = list(drSheldon, drLeonard, drRaj);
List<Person> people = list(sheldon, leonard, raj);
RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
.withIgnoredFields("hasPhd")
.build();
// assertion succeeds as both lists contains equivalent items in order.
assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
.contains(sheldon);
See https://assertj.github.io/doc/#assertj-core-recursive-comparison-for-iterable for a more detailed explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With