Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assertj: How to compare 2 objects list by objects content?

Tags:

java

assertj

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));
}
like image 435
dushkin Avatar asked Feb 19 '26 22:02

dushkin


1 Answers

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.

like image 104
Joel Costigliola Avatar answered Feb 22 '26 11:02

Joel Costigliola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!