Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit and Netty cause application to end prematurely

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();
    }
}
like image 498
durron597 Avatar asked Oct 05 '22 00:10

durron597


1 Answers

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.

  • If you just need to test that your server can start, then your current test does just that. In particular, the link you provide shows a server that runs in a background thread so the run method returns immediately. So your test checks that the run method returns without problems.
  • If you want to actually exercise your server by sending data and checking what is received (for example). In that case, you need to include the code that tests the server in the same test method.

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)

like image 117
assylias Avatar answered Oct 13 '22 12:10

assylias