Note: I am using JUnit 4.11 and Netty 3.6.5.
I am trying to test some basic functionality in my complicated server app. I want to extract simply the networking functionality and do some unit tests. However, when I try to create a unit test, the application simply exits. However, if I put a dummy public static void main
, it works correctly, but outside of JUnit, obviously. Here's the sscce:
public class SimpleNetwork {
private Injector inj;
@Before
public void startInjector() {
Module mod = new AbstractModule() {
@Override
protected void configure() {
// Guice stuff you don't need to see, it works fine
}
};
inj = Guice.createInjector(mod);
}
// **When I run this using JUnit, the application ends immediately.**
@Test
public void testNetwork() {
NioServer server = inj.getInstance(NioServer.class);
server.run();
// **This prints in both scenarios**
System.out.println("Hello World");
}
// **When I run this, the application works as expected.**
public static void main(String[] args) {
SimpleNetwork sn = new SimpleNetwork();
sn.startInjector();
sn.testNetwork();
}
}
Junit will exit the test as soon as the junit thread is done whereas your main will wait for non daemon threads to terminate before exiting. You need to pause the junit thread and wait for whatever event to happen.
It is not clear what you are trying to test.
run
method returns immediately. So your test checks that the run
method returns without problems.A more typical way of testing something like that would be to start the server once for the whole test class:
private NioServer server;
@BeforeClass
public void beforeClass() {
server = getServer();
server.run();
}
@Test
public void testOne() {
sendSomeDataToServer("data");
assertEquals("data", server.getLastReceivedData());
}
(I am not 100% sure about the JUnit syntax as I use testNG but it should be something like that)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With