Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertEquals when list content is unordered [duplicate]

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.

like image 268
Baz Avatar asked Mar 10 '17 09:03

Baz


People also ask

How do you use assertEquals with a list?

Using JUnit We can use the logic below to compare the equality of two lists using the assertTrue and assertFalse methods. In this first test, the size of both lists is compared before we check if the elements in both lists are the same. As both of these conditions return true, our test will pass.

Does Assertequal work on lists?

To compare two lists specifically, TestNG's Assert class has a method known as assertEquals(Object actual, Object expected) and there is an extended version of this method with customized message as assertEquals(Object actual, Object expected, String message). if the elements of the lists are in the same order.

Can assertEquals compare objects?

assertEquals. Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null , they are considered equal.

What is the difference between assertEquals and assertSame?

assertEquals() Asserts that two objects are equal. assertSame() Asserts that two objects refer to the same object. the assertEquals should pass and assertSame should fail, as the value of both classes are equal but they have different reference location.


1 Answers

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"));
like image 187
Thirler Avatar answered Oct 26 '22 23:10

Thirler