I'm trying to use Mockito to create a Mock object that gets returned from a Mock object. Specifically, I'm trying to mock a PlayerConnection
object that my program can use to retrieve an IP address.
You can find more about this PlayerConnection object
here. It returns an InetSocketAddress
which can then return an InetAddress
that can return a String
with the IP of the player. But I can't get that far, because my first when(class.function()).thenReturn(returnVariable)
throws a NullPointerException
. Here's my code:
/**
* Creates a partial mock of a connection that can return an ip address.
*
* @param String
* The IP to return when the connection gets asked.
* @return
*/
private PlayerConnection newConnection(String ipString)
{
PlayerConnection playerConnection = mock(PlayerConnection.class);
InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class);
InetAddress inetAddress = mock(InetAddress.class);
when(playerConnection.getAddress()).thenReturn(inetSocketAddress);
when(inetSocketAddress.getAddress()).thenReturn(inetAddress);
when(inetAddress.getHostAddress()).thenReturn(ipString);
return playerConnection;
}
And here's the stack trace, occuring at when(playerConnection.getAddress()).thenReturn(inetSocketAddress)
:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.001 sec <<< FAILURE!
ruleResponseTest(com.github.heartsemma.communitywall.ConnectionChecks.RuleManagerTest) Time elapsed: 0.001 sec <<< ERROR!
java.lang.NullPointerException
at java.net.InetSocketAddress$InetSocketAddressHolder.access$500(InetSocketAddress.java:56)
at java.net.InetSocketAddress.getAddress(InetSocketAddress.java:334)
at com.github.heartsemma.communitywall.ConnectionChecks.RuleManagerTest.newConnection(RuleManagerTest.java:99)
at com.github.heartsemma.communitywall.ConnectionChecks.RuleManagerTest.ruleResponseTest(RuleManagerTest.java:44)
Edit:
I have switched my stubs to doReturn().when().function()
instead of when().thenReturn()
to stop the NullPointerExceptions
, and it did, but now I am getting custom UnfinishedStubbingExceptions
from Mockito.
The helpful error code says that I have an unfinished stub somewhere, but I don't see where it is. The error occurs on the second doReturn()
method.
/**
* Creates a partial mock of a connection that can return an ip address.
*
* @param ipString The IP to return.
*
* @return A PlayerConnection object that can return a Host Address of the ipString but nothing else.
*/
private PlayerConnection newConnection(String ipString)
{
PlayerConnection playerConnection = mock(PlayerConnection.class);
InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class);
InetAddress inetAddress = mock(InetAddress.class);
doReturn(inetSocketAddress).when(playerConnection).getAddress();
doReturn(inetAddress).when(inetSocketAddress).getAddress();
doReturn(ipString).when(inetAddress).getHostAddress();
return playerConnection;
}