Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionAssert in jUnit?

Is there a jUnit parallel to NUnit's CollectionAssert?

like image 752
ripper234 Avatar asked Jul 06 '09 12:07

ripper234


People also ask

How do I compare lists in Junit?

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.

How do you assert a list of objects in Junit?

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.

How do you compare two lists with assert?

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.


2 Answers

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.

like image 95
Joachim Sauer Avatar answered Sep 28 '22 05:09

Joachim Sauer


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)

like image 37
skaffman Avatar answered Sep 28 '22 05:09

skaffman