Answer the question
In order to leave comments, you need to log in
How to write tests for client-server connection (sockets)?
Good afternoon! I am writing a client-server application. I try to cover all code with unit tests. The only thing that cannot be automated so far is the simultaneous launch of the server and the client with the exchange of some data. You have to manually start the server and client each time and manually enter data in the client, which is very tiring. Here is a rough sketch of how I thought to implement it:
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
@BeforeClass
public static void startServer() {
ServerSocket listener = null;
try {
listener = new ServerSocket(5050);
while (true) {
try {
Socket socket = listener.accept();
System.out.println("Client connected");
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
try {
String request = dis.readUTF();
System.out.println(request);
dos.writeUTF(request);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void checkServerResponse() {
try {
Socket socket = new Socket("127.0.0.1", 5050);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
String request = "Hello";
dos.writeUTF(request);
String serverResponse = dis.readUTF();
Assert.assertEquals("Hello", serverResponse);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question