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
Any idea what I am doing wrong?
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()));
EDIT: 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.
The signatures for bind
are bind(java.net.SocketAddress)
or bind(java.net.SocketAddress,int)
, but you're giving it a java.lang.Object
.
If you're sure that the runtime type returned by any()
is a java.net.SocketAddress
, you can cast it:
ssc.socket().bind((SocketAddress)any(), anyInt())
(Of course, if it's not you'll get a ClassCastException
.)
精彩评论