churay
churay

Reputation: 440

Stubbing Out a Null-Returning Function in Mockito

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.

Upvotes: 2

Views: 736

Answers (2)

sam
sam

Reputation: 118

If you do a view source you will notice that the method is final.

public final Object readObject()

Try wrapping the dependency with another object. See: Final method mocking

Upvotes: 2

nansen
nansen

Reputation: 2962

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.

Upvotes: 2

Related Questions