用Mockito模拟Java中的套接字

编程入门 行业动态 更新时间:2024-10-27 12:32:32
本文介绍了用Mockito模拟Java中的套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试模拟以下呼叫:

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.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中的套接字

本文发布于:2023-10-31 07:08:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545384.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Mockito   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!