简体   繁体   English

如何模拟java socket连接中断?

[英]How to simulate java socket connection break?

I have written java application that makes socket connections with a legacy system. 我编写了java应用程序,它与遗留系统建立套接字连接。

How can I simulate the connection failure (Eg Socket connection timeout, read timeout, network failure) , so that i can add necessary code based on the exception trace ? 如何模拟连接失败(例如套接字连接超时,读取超时,网络故障) ,以便我可以根据异常跟踪添加必要的代码?

Do you want to trigger an actual failure or test your code works in different situations? 您是否想要触发实际故障或测试您的代码在不同情况下的工作情况?

If its the latter, I would create a simple mock server, or if this is not practical, a proxy server. 如果是后者,我会创建一个简单的模拟服务器,或者如果这不实用,则创建一个代理服务器。 Close the outbound or incoming connection, or stop sending data at a certain point. 关闭出站或传入连接,或停止在某一点发送数据。 At this point you can test your code behaves as expected. 此时,您可以按预期测试代码的行为。

Use a mock framework such as Mockito or EasyMock, mock a Socket object. 使用模拟框架,如Mockito或EasyMock,模拟一个Socket对象。

Look at the Javadoc for Socket and make your mocked object fail at some point with an Exception thrown by it in your unit tests. 查看Javadoc for Socket并使你的模拟对象在某些时候失败,并在单元测试中抛出它的Exception。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM