views:

30

answers:

2

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?

+1  A: 

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.

Matthew Flaschen
Sorry, was not clear enough. I know why it is not working, I am unsure how to make it work with mockito's matchers.
Sardathrion
Right, that appear to have solved it. I just did not need it. Strange behaviour if you ask me but hey, what do I know?Thanks!
Sardathrion
+1  A: 

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.)

Bruno
(I'm not quite sure how Mockito works, but it looks like any() is parametrized, you you've probably got something wrong in the way you use it.)
Bruno
Do you use any() via a static import? Perhaps any(SocketAddress.class) would help?
Bruno
doNothing().when(ssc.socket().bind((SocketAddress)any(SocketAddress.class), anyInt()));gives me a 'void' type not allowed here. However, I think this is the right track.
Sardathrion