Mocking sockets in java with mockito

I am trying to make fun of the following call:

s.socket().bind(new InetSocketAddress(serverIPAddress_, serverPort_), 0);

so I can check what the rest of the code does when it fails in a predictable way. 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'm doing wrong?

+2
source share
2 answers

ServerSocketdoes not have a binding overload that accepts an object and an int. It has an overload that accepts SocketAddressint as well. I have not used Mockito, but I think you might need:

doNothing().when(ssc.socket().bind(isA(ServerSocket.class), anyInt()));

EDIT: , void when. docs note, "void mocks .", .

+1

bind bind(java.net.SocketAddress) bind(java.net.SocketAddress,int), java.lang.Object.

, , any(), java.net.SocketAddress, :

ssc.socket().bind((SocketAddress)any(), anyInt())

(, , ClassCastException.)

+1

All Articles