I am trying to use Mockito to create a Mock object that is returned from a Mock object. In particular, I am trying to make fun of the PlayerConnection object that my program can use to obtain an IP address.
Read more about this PlayerConnection object here . It returns an InetSocketAddress , which can then return an InetAddress , which can return a String with the IP address of the player. But I can't go that far, because my first when(class.function()).thenReturn(returnVariable) throws a NullPointerException . Here is my code:
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 is the stack trace when(playerConnection.getAddress()).thenReturn(inetSocketAddress) place in 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 switched my stubs to doReturn().when().function() instead of when().thenReturn() to stop NullPointerExceptions , and this happened, but now I get a custom UnfinishedStubbingExceptions from Mockito.
A useful error code says that I have an incomplete stub somewhere, but I donβt see where it is. The error occurs in the second doReturn() method.
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; }
source share