我有一个类是套接字客户端,我正在尝试对其方法进行单元测试。测试要求我在每次测试之前启动一个套接字服务器,所以我使用:
@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
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.
}
}
}
但是,在从第二个测试开始的每个测试之前,我都会收到“java.net.BindException:地址已在使用:JVM_Bind”。我意识到我正在尝试为每个测试使用相同的端口,但不应该关闭套接字以释放端口?