Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit: testing an object is not in a list

Tags:

java

list

junit

In JUnit tests, I need to test that a given object (not the reference, but the attributes of the object) is not in a list. What's the best way to do that?

like image 523
Alexis Dufrenoy Avatar asked Oct 28 '25 07:10

Alexis Dufrenoy


2 Answers

Assuming you're using a current version of JUnit, the best way to do it would be to write your own Matcher for a list of objects of your type.

Create a class extending org.hamcrest.TypeSafeMatcher and implement the methods given. Add a static constructor method for your class, so you can easily call it in your assertThat statement and hand over a example of the object that should not be contained. In the matchesSafely() method, assure that your list contains no object that matches the attributes of your sample.

As an alternative, implement equals on your object, create a sample and then do assertThat(yourList,not(hasItem(yourSample)));, where not is a static import from CoreMatchers, and hasItem is a static import from JUnitMatchers.

Of course, once you implement equals you can simple assertFalse(yourList.contains(yourSample));

like image 86
Urs Reupke Avatar answered Oct 31 '25 11:10

Urs Reupke


If I understand your question properly:

Object o =....; //some object
assertFalse(list.contains(o));

This can work if the object equals() method has been properly implemented.

like image 29
Buhake Sindi Avatar answered Oct 31 '25 12:10

Buhake Sindi