小编J. *_*Doe的帖子

Mockito when().thenReturn()抛出nullpointerExceptions

我正在尝试使用Mockito创建一个从Mock对象返回的Mock对象.具体来说,我正在尝试模拟PlayerConnection我的程序可以用来检索IP地址的对象.

你可以PlayerConnection object 在这里找到更多相关信息.它返回一个InetSocketAddress然后InetAddress可以返回一个可以返回String与播放器的IP的a .但我无法走得那么远,因为我的第一次when(class.function()).thenReturn(returnVariable)投掷了NullPointerException.这是我的代码:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪,发生在when(playerConnection.getAddress()).thenReturn(inetSocketAddress):

Tests run: 1, …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mockito

5
推荐指数
1
解决办法
2110
查看次数

标签 统计

java ×1

mockito ×1

unit-testing ×1