Consider the following class:
public class Node {
private final Collection<Node> mDependants = new ArrayList<>();
private Node mDependency;
public void initialize(final Node node) {
// complex code that might call registerDependency;
}
private void registerDependency(final Node node) {
mDependency = node;
node.registerDependent(this);
}
private void registerDependent(final Node node) {
mDependants.add(node);
}
}
And then a unit test like:
import static org.mockito.Mockito.mock;
public class NodeTest {
private Node mTarget;
private Node mDependent;
@Before
public void setUp() {
mTarget = new Node();
mDependent = mock(Node.class);
}
@Test
public void test() {
mTarget.initialize(mDependent);
}
}
Since registerDependent is private, mockito will not actually mock it. Since the mTarget is actually a real instance, when the registerDependency method is executed via initialize, it will try to execute the private method registerDependent on the mock. The mock being a mock will not be initialized and mDependants will actually be null causing a NullPointerException on mDependats.add(node).
What should be the correct way to test this? Should I use two real Nodes instead of a mock? should I make the methods public to allow the mocking of the method? Is there another option I'm missing?final Node node