I’m writing a junitTest that should test a serverHandler object that handle the reciving and sending of message to a server.
I’m doing that by mocking the socket of the server and putting my own ObjectInputStream and ObjectOutputStream so that I will be able to controll what message the server is sending.
I cant wrap my head why the “output” object in the serverHandler is created and is set as ObjectOutputStream created in the test, while the “input” object remains null and blocks the code flow until the timer in executor runs up and stop the thread.
I already experimented by writing some “initialData” in the outputPipe, because I read that the constructor of the ObjectInputStream can block the code flow, but by doing that I got hit with the: java.io.EOFException. The problem is that, when connected to the real SocketServer, the serverHandler runs just fine. Below the code implementation for the test and the serverHandler
public class ServerHandlerTest {
@Test
public void testServerHandler() {
PipedInputStream inputPipe = new PipedInputStream();
PipedOutputStream outputPipe = new PipedOutputStream();
try{
inputPipe.connect(outputPipe);
} catch (Exception e) {
e.printStackTrace();
}
ObjectInputStream input;
ObjectOutputStream output;
try {
output = new ObjectOutputStream(outputPipe);
output.writeObject("Initial Data");
output.flush();
input = new ObjectInputStream(inputPipe);
} catch (Exception e) {
e.printStackTrace();
return;
}
Socket mockServer = mock(Socket.class);
try{
when(mockServer.getOutputStream()).thenReturn(output);
when(mockServer.getInputStream()).thenReturn(input);
} catch (Exception e) {
e.printStackTrace();
}
when(mockServer.getInetAddress()).thenReturn(null);
ServerHandler serverHandler = new ServerHandler(mockServer);
Thread serverHandlerThread = new Thread(serverHandler, "testedServerHandler");
serverHandlerThread.start();
try {
serverHandlerThread.join(); // wait for the serverHandlerThread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
serverHandler run() method:
public void run(){
ExecutorService executor = Executors.newSingleThreadExecutor();
try{
Future<?> future = executor.submit(() -> {
try {
output = new ObjectOutputStream(server.getOutputStream());
input = new ObjectInputStream(server.getInputStream());
System.out.println("Connected to " + server.getInetAddress());
}catch (IOException e) {
try {
System.out.println("Error while creating the input and output streams");
} catch (Exception ex) {
//This is socket, RemoteException should not be thrown
throw new RuntimeException(ex);
}
}
});
future.get(5, TimeUnit.SECONDS);
}catch (TimeoutException e) {
//todo: implementaion of what will if the timers run up
}
Samuele is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.