In 开发者_StackOverflow中文版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.
I assume doing a simple contains() is not a deep enough check? If you've overriden your object's equals() method already then list.contains( o ) would work.
@Test
public void testContains() {
String demoObject = "Testing!";
//myList isa List<String>
assertFalse("Object was in collection", myList.contains(demoObject));
}
If the Objects you store in the List implement equals
to match these attributes, then list.contains(o) or list.indexOf(o) will give you the answer.
If your objects do not implement equals, then these methods will answer based on reference equality (not what you want).
If I understand you want to assert that a property of some objects in a list isn't equals at something.... if you can user the commons collection ( http://commons.apache.org/collections/ ) you can use the interface org.apache.commons.collections.Predicate to search in a list (using the method org.apache.commons.collections.CollectionUtils.find(List, Predicate)
you can make somenthing like
Predicate p = new Predicate(){ /* * Test if the object has the value that you don't want */ public boolean evaluate(java.lang.Object object){ YourObject yo = (YourObject) object; return yo.getProperty().equals(theValue); } } //if is return null means that nothing was found assertNull(CollectionUtils.find(yourList, p));
精彩评论