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.
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"));
I would recommend using AssertJ -
import static org.assertj.core.api.Assertions.assertThat;
// ......
List<String> products = get_products("test_produc").stream()
.map(Product::getName)
.collect(toList());
assertThat(products).containsExactlyInAnyOrder("Third", "Second", "First");
which additionally gives you many more fluent assertions (especially the exception handling ones) as well.
I'd combine the answer of Abubakkar with Hamcrest compare collections
List<String> productNames = products.stream()
.map(p -> p.getName())
.collect(Collectors.toList());
// assert that the actual list does not contain additional elements:
assertEquals(products.size(),3);
assertThat(productNames, containsInAnyOrder("test_product1", "test_product2", "test_produc3"));