I’ve been using JUnit and Mockito in an attempt to test how a particular networking module affects its input and output streams. To facilitate testing, I’ve created a set of mock network object streams (i.e. an instance of an ObjectInputStream and an instance of an ObjectOutputStream) and stubbed out the methods I want to be testing in a fashion similar to the following code snippet:
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import static org.mockito.Mockito.*;
import org.junit.Test;
public class NetworkTester
{
@Test
public void ModuleRespondsToServerRequest() throws Exception
{
ObjectInputStream mockClientIn = mock(ObjectInputStream.class);
ObjectOutputStream mockClientOut = mock(ObjectOutputStream.class);
when(mockClientIn.readObject()).thenReturn("Sent from Server");
// Initialize module and connect it to the network...
verify(mockClientOut, timeout(100).atLeastOnce()).writeObject(isNotNull());
}
}
However, when I try to compile and run this code, I get a null pointer exception at the line “when(mockClientIn.readObject()).thenReturn(“Sent from Server”);”. I believe that this is caused by the fact that the “readObject()” function is returning a null pointer when called on the stubbed object, but I don’t know if it’s possible to bypass this behavior.
Is there any way to stub this function (or similar null returning functions) using Mockito? Thanks in advance for your help.
Mockito cannot mock
readObject()since it is final. You could try PowerMockito or consider redesigning your code for easier testability. See a discussion on the topic here.