AssertEquals when list content is unordered

Baz picture Baz · Mar 10, 2017 · Viewed 10.6k times · Source

How would you refactor the following if the products can be returned in any order?

List<Product> products = get_products("test_produc");
assertEquals(products.size(),3);
assertEquals(products.get(0).getName(), "test_product1");
assertEquals(products.get(1).getName(), "test_product2");
assertEquals(products.get(2).getName(), "test_produc3");

If it can be done elegantly using streams then I'm oopen to such suggestions. Hamcrest suggestions are also welcome.

Answer

Thirler picture Thirler · Mar 10, 2017

Note that assertEquals also works on Lists and Sets directly. This is much less typing and it will give very clear error messages.

If the return values are not allowed to contain duplicates, they should return a Set instead of a List. If you can change the function you are testing is this way you can test it as follows:

assertEquals(new HashSet<>(Arrays.asList("Item1", "Item2")), get_products());

If this is not an option you should sort both the expected and the actual results and compare those:

asssertEquals(Arrays.sort(Arrays.asList("Item1", "Item2")), Arrays.sort(get_products()));

Finally you could resort to using Hamcrest matchers (the function containsInAnyOrder is in org.hamcrest.collection.IsIterableContainingInAnyOrder):

assertThat(get_products(), containsInAnyOrder("Item1", "Item2"));