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)
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,但它应该是类似的东西)
| 归档时间: |
|
| 查看次数: |
848 次 |
| 最近记录: |