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?
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));
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.
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