Home > Software design >  How can I compare two collections using == with AssertJ?
How can I compare two collections using == with AssertJ?

Time:10-10

I just implemented my own Insertion sort and trying to verify functionalities including stability.

For a given list of unsorted elements, I'm trying to verify my code against Collections#sort(List) method.

List<E> unsorted = ...; // <E extends Comparable<? super E>>

List<E> sorted1 = new ArrayList<>(unsorted);
Collections.sort(sorted1);

List<E> sorted2 = new ArrayList<>(unsorted);
MyInsertionSort.sort(sorted2);

I found AbstractIterableAssert#containsExactlyElementsOf method.

        assertThat(sorted2)
                .isSorted()
                .isSortedAccordingTo(Comparator.naturalOrder())
                .containsExactlyElementsOf(sorted1)
        ;

I ended up while tracing the method to the point calling Comparator#compare.

Is the containsExactlyElementsOf method covers the stability?

Or is there any other method should I add for the stability?

CodePudding user response:

you can use hasSameElementsAs() method from AssertJ. This method ignores the duplicates and validates both has same elements assertThat(firstCollection).hasSameElementsAs(secondCollection); It is advised to validate the size first when we go for this method.

If you worry about the order then we can use containsExactlyInAnyOrde()

CodePudding user response:

I'm not sure I can confirm/find any way.

I just tried following simple loop.

for (int i = 0; i < sorted2.size(); i  ) {
    assertThat(sorted2.get(i))
            .isSameAs(sorted1.get(i));
}
  • Related