问题描述
我正在尝试模拟以下呼叫:
I am trying to mock the following call:
s.socket().bind(new InetSocketAddress(serverIPAddress_, serverPort_), 0);
因此,我可以以可预测的方式测试当其余代码失败时其余代码的功能.我在测试用例中使用它:
so I can test what the rest of the code does when this fails in predictable ways. I use this in my test case:
ServerSocketChannel ssc = mock(ServerSocketChannel.class);
when(ServerSocketChannel.open()).thenReturn(ssc);
doNothing().when(ssc.socket().bind(any(), anyInt()));
但是,以上内容无法与以下内容一起编译:
However, the above does not compile with:
[javac] /home/yann/projects/flexnbd/src/uk/co/bytemark/flexnbd/FlexNBDTest.java:147: cannot find symbol
[javac] symbol : method bind(java.lang.Object,int)
[javac] location: class java.net.ServerSocket
[javac] doNothing().when(ssc.socket().bind(any(), anyInt()));
[javac] ^
[javac] 1 error
知道我在做什么错吗?
推荐答案
ServerSocket
没有使用对象和整数的绑定重载.它有一个需要SocketAddress
和一个int的重载.我没有使用过Mockito,但我认为您可能需要:
ServerSocket
has no bind overload that takes an Object and an int. It has an overload that takes a SocketAddress
and an int. I haven't used Mockito, but I think you may need:
doNothing().when(ssc.socket().bind(isA(ServerSocket.class), anyInt()));
最新错误是因为您试图将void传递给when方法. 文档说明,默认情况下,模拟方法上的void方法不执行任何操作.",因此您可能根本不需要此行.
The latest error is because you're trying to pass void to the when method. The docs note, "void methods on mocks do nothing by default.", so you may not need this line at all.
这篇关于用Mockito模拟Java中的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!