Issue
How can I start a separate thread which runs my project's main class from within a Junit test?
I have a main class that instantiates Servidor()
which ends up listening for socket connections, and works fine.
Here's Main:
public class Main {
public static void main(String[] args){
try{
Servidor servidor = new Servidor();
servidor.start();
}catch(Exception ex){
MyUtils.handle(ex);
}
}
}
Here's Servidor()
:
public class Servidor extends javax.swing.JPanel {
private static final int PUERTO = 2020;
private boolean running = false;
void start() throws Exception{
try ( ServerSocket servidor = new ServerSocket(PUERTO) ){
running = true;
String info = String.format("Listening@%s:%s",InetAddress.getLocalHost().getHostAddress(),PUERTO);
System.out.println(info);
while (running)
new ReceptorPedidosReplicacion(servidor.accept());
System.out.println("Server Stopped");
}
}
void stop(){
running = false;
}
}
However, I designed the following Junit test and as expected, it works fine as long as I have my project running in the background:
public class ServidorTest {
@Test
public void testSendPedido() throws Exception{
MySerializableObject pedido = new MySerializableObject();
Socket cliente = new Socket("127.0.0.1", 2020);
ObjectOutputStream out = new ObjectOutputStream(cliente.getOutputStream());
out.writeObject(pedido);
}
}
So what I would like to do is to be able to do something like:
@Test
public void testSendPedido() throws Exception{
Main.main(); //Option1
new Servidor().start(); //Option 2
MySerializableObject pedido = new MySerializableObject();
Socket cliente = new Socket("127.0.0.1", 2020);
ObjectOutputStream out = new ObjectOutputStream(cliente.getOutputStream());
out.writeObject(pedido);
}
However neither option works because Servidor()
hijacks the execution thread and the test never gets past those lines.
Solution
Got around to it by making Servidor()
implement Runnable
and starting a different thread from the Junit. However, I'm not sure if Junit will handle such new threads safely. I'm guessing I'll be fine as long Servidor
has no critical state changes. However I'm open to a better solution.
public class Servidor extends javax.swing.JPanel implements Runnable{
...
public void run(){start()}
}
So the test looks like this
@Test
public void testSendPedido() throws Exception{
Thread thread = new Thread(new Servidor());
thread.start();
...
}
Answered By - LeedMx