Is there a jUnit parallel to NUnit's CollectionAssert
?
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.
You can use assertEquals in junit. If the order of elements is different then it will return error. If you are asserting a model object list then you should override the equals method in the specific model. Save this answer.
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.
Using JUnit 4.4 you can use assertThat()
together with the Hamcrest code (don't worry, it's shipped with JUnit, no need for an extra .jar
) to produce complex self-describing asserts including ones that operate on collections:
import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; List<String> l = Arrays.asList("foo", "bar"); assertThat(l, hasItems("foo", "bar")); assertThat(l, not(hasItem((String) null))); assertThat(l, not(hasItems("bar", "quux"))); // check if two objects are equal with assertThat() // the following three lines of code check the same thing. // the first one is the "traditional" approach, // the second one is the succinct version and the third one the verbose one assertEquals(l, Arrays.asList("foo", "bar"))); assertThat(l, is(Arrays.asList("foo", "bar"))); assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));
Using this approach you will automagically get a good description of the assert when it fails.
Not directly, no. I suggest the use of Hamcrest, which provides a rich set of matching rules which integrates nicely with jUnit (and other testing frameworks)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With