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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.TypeSafeMatcherand implement the methods given.Add a static constructor method for your class, so you can easily call it in your
assertThatstatement 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
equalson your object, create a sample and then doassertThat(yourList,not(hasItem(yourSample)));, wherenotis a static import fromCoreMatchers, andhasItemis a static import fromJUnitMatchers.Of course, once you implement
equalsyou can simpleassertFalse(yourList.contains(yourSample));