11

I am looking to compare 2 list of objects (say Foo) in test.

List<Foo> fooA;
List<Foo> fooB;

Each Foo entry has one of the fields of type List (say Bar)

class Foo {
  private List<Bar> bars;
  ....
}

assertThat(fooA).isEqualTo(fooB);

Comparison fails because elements of bars are same but in different order.

Is there a way to compare them ignoring order?

I am not looking for below option.

assertThat(fooA).usingElementComparatorIgnoringFields("bars").isEqualTo(fooB);

Ideally I would like to compare all the fields

Random
  • 325
  • 1
  • 3
  • 15

2 Answers2

8

you can do this with assertJ:

assertThat(fooA).usingRecursiveComparison().ignoringCollectionOrder().isEqualTo(fooB)
alampada
  • 2,329
  • 1
  • 23
  • 18
  • 1
    Recursive comparison allows you to compare field by field recursively even if they were not of the same type. – IamDOM Jun 10 '22 at 12:04
4

What you are looking for is containsExactlyInAnyOrderElementsOf(Iterable) defined in IterableAssert (emphasis is mine) :

Verifies that the actual group contains exactly the given values and nothing else, in any order.

You could write so :

List<Foo> fooA;
List<Foo> fooB;
//...
assertThat(fooA).containsExactlyInAnyOrderElementsOf(fooB);
davidxxx
  • 125,838
  • 23
  • 214
  • 215