Class A has inner class B. Class A has a private list of class B objects that it makes available through getBs, addB, and removeB methods. How do I unit test the removeB method?
I was hoping to create two equal mocks of class B, add each, and then remove one of them twice (result being to remove both). However, I've since learned through failure that the equals method will not be called on mock objects.
Was it foolish (or impossible) to try and isolate an outer class from its inner class for unit testing?
Sample code follows
Class to test:
import java.util.ArrayList;
import java.util.List;
public class Example {
private List<Inner> inners = new ArrayList<Inner>();
public List<Inner> getInners() {
return inners;
}
public void addInner(Inner i) {
inners.add(i);
}
public void removeInner(Inner i) {
inners.remove(i);
}
/**
* equalityField represents all fields that are used for testing equality
*/
public class Inner {
private int equalityField;
private int otherFields;
public int getEqualityField() {
return equalityField;
}
public Inner(int field) {
this.equalityField = field;
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (o.getClass() != this.getClass())
return false;
Inner other = (Inner) o;
if (equalityField == other.getEqualityField())
return true;
return false;
}
}
}
Test case that didn't work out so great:
import static org.junit.Assert.*;
import org.junit.Test;
import org.easymock.classextension.EasyMock;
public class ExampleTest {
@Test
public void testRemoveInner() {
Example.Inner[] mockInner = new Example.Inner[2];
mockInner[0] = EasyMock.createMock(Example.Inner.class);
mockInner[1] = EasyMock.createMock(Example.Inner.class);
Example e = new Example();
e.addInner(mockInner[0]);
e.addInner(mockInner[1]);
e.removeInner(mockInner[0]);
e.removeInner(mockInner[0]);
assertEquals(0, e.getInners().size());
}
}