JUnit和Netty导致应用程序过早结束

dur*_*597 5 java junit multithreading netty

注意:我使用的是JUnit 4.11和Netty 3.6.5.

我试图在我复杂的服务器应用程序中测试一些基本功能.我想简单地提取网络功能并进行一些单元测试.但是,当我尝试创建单元测试时,应用程序只是退出.但是,如果我放一个假人public static void main,它可以正常工作,但显然在JUnit之外.这是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();
    }
}
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 4

Junit 线程完成后将立即退出测试,而 main 将等待非守护线程终止后再退出。您需要暂停 junit 线程并等待任何事件发生。

目前尚不清楚您要测试什么。

  • 如果您只需要测试服务器是否可以启动,那么您当前的测试就可以做到这一点。特别是,您提供的链接显示了一个在后台线程中运行的服务器,因此该run方法立即返回。因此,您的测试会检查该run方法是否毫无问题地返回。
  • 如果您想通过发送数据并检查收到的内容来实际锻炼您的服务器(例如)。在这种情况下,您需要在同一测试方法中包含测试服务器的代码。

测试此类内容的更典型方法是为整个测试类启动一次服务器:

private NioServer server;
@BeforeClass
public void beforeClass() {
    server = getServer();
    server.run();
}

@Test
public void testOne() {
    sendSomeDataToServer("data");
    assertEquals("data", server.getLastReceivedData());
}
Run Code Online (Sandbox Code Playgroud)

(我对 JUnit 语法不是 100% 确定,因为我使用 testNG,但它应该是类似的东西)