kris82pl
kris82pl

Reputation: 1109

Sorting array before compare in AssertJ

I compare two objects using assertJ. I have actual object which is output from our application and expected object. This object has field which is an array of other object but elements in this array are present in random order so sometimes test passes but also often is failed because incorrect elements of array are compared.

What I'm doing I get arrays from both objects sort them and then set to objects but this looks ugly and uses 7 lines of code.

Comparator.comparing(Value::getId)

Value[] actualOrderChildren = actualOrder.getChildren();
Arrays.sort(actualOrderChildren, comparing);
actualOrder.setChildren(actualOrderChildren);

Value[] expectedOrderChildren = expectedOrder.getChildren();
Arrays.sort(expectedOrderChildren, comparing);
expectedOrder.setChildren(expectedOrderChildren);

assertThat(actualOrder).isEqualToComparingFieldByFieldRecursively(expectedOrder);

Is there any better looking solution using assertj fluent assertions ?

Upvotes: 0

Views: 502

Answers (1)

Sebastien
Sebastien

Reputation: 6542

containsExactlyInAnyOrder is probably what your are looking for.

assertThat(actualOrder.getChildren()).containsExactlyInAnyOrder(expectedOrder.getChildren());

Upvotes: 1

Related Questions