[英]unit testing sockets in java
I have a class which is a socket client and I am trying to unit test its methods. 我有一个类是一个套接字客户端,我试图对其方法进行单元测试。 The tests require that I start a socket server before each test so I use:
测试要求我在每次测试之前启动套接字服务器,所以我使用:
@Before
public void setUp() {
if (myServerSocket == null) {
Thread myThread = new Thread() {
public void run() {
DataInputStream dis = null;
DataOutputStream dos = null;
try {
ServerSocket myServer = new ServerSocket(port);
myServerSocket = myServer.accept();
dis = new DataInputStream(myServerSocket.getInputStream());
dos = new DataOutputStream(myServerSocket.getOutputStream());
byte[] bytes = new byte[10];
dis.read(bytes);
boolean breakLoop = false;
do {
if (new String(bytes).length() != 0) {
dos.writeBytes(serverMessage + "\n");
dos.flush();
breakLoop = true;
dos.writeBytes("</BroadsoftDocument>" + "\n");
dos.flush();
}
} while (!breakLoop);
}
catch (IOException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
After each test I try to close the server socket so I can reopen the server socket for the next test: 在每次测试后,我尝试关闭服务器套接字,以便我可以重新打开服务器套接字以进行下一个测试:
@After
public void tearDown() throws IOException, BroadsoftSocketException {
System.out.println("@After");
if (myServerSocket != null) {
myServerSocket.close();
myServerSocket = null;
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// do nothing.
}
}
}
However, I get "java.net.BindException: Address already in use: JVM_Bind" before each test starting with the second test. 但是,在第二次测试开始的每次测试之前,我得到“java.net.BindException:Address in in use:JVM_Bind”。 I realize I am trying to use the same port for each test but shouldn't closing the socket free up the port?
我意识到我试图为每个测试使用相同的端口,但是不应该关闭套接字释放端口?
Quite possibly your socket is still in TIME_WAIT
state when you attempt to reconnect it. 当您尝试重新连接时,您的套接字可能仍处于
TIME_WAIT
状态。 I would recommend mocking such external dependencies, but if you really do find yourself wanting to continue using a real socket then try setting rebind options. 我建议模拟这样的外部依赖项,但如果你确实发现自己想要继续使用真正的套接字,那么尝试设置重新绑定选项。 In your setup function, instead of
ServerSocket myServer = new ServerSocket(port);
在您的安装功能中,而不是
ServerSocket myServer = new ServerSocket(port);
do : 做:
final ServerSocket myServer = new ServerSocket();
myServer.setReuseAddress(true);
myServer.bind(new java.net.InetSocketAddress(port));
finally
block. finally
块中执行它。 ServerSocket
's reuseAdress to true
. ServerSocket
的reuseAdress设置为true
来避免这种true
。 See setReuseAddress . And I second SimonC: maybe you are better off avoiding the socket in the first place. 而我第二个SimonC:也许你最好先避开套接字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.