如何使用junit测试阻塞方法

Bwi*_*ire 3 java junit unit-testing

我有一个类,有一个阻止的方法,并希望验证它是阻塞的.方法如下所示.

 public static void main(String[] args) {

    // the main routine is only here so I can also run the app from the command line
    applicationLauncherInstance.initialize();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            if (null != application) {
                applicationLauncherInstance.terminate();
            }
        }
    });

    try {
        _latch.await();
    } catch (InterruptedException e) {
        log.warn(" main : ", e);
    }
    System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)

如何为这种方法编写单元测试.我在开始前被卡住了.

public class ApplicationLauncherTest extends TestCase {


    public void testMain() throws Exception {
        ApplicationLauncher launcher = new ApplicationLauncher();
    }
}
Run Code Online (Sandbox Code Playgroud)

Bwi*_*ire 5

感谢Kulu,我找到了解决方案.

public void testMain() throws Exception {
    Thread mainRunner = new Thread(() -> {
        ApplicationLauncher.main(new String[]{});
    });

    mainRunner.start();

    Thread.sleep(5000);

    assertEquals(Thread.State.WAITING, mainRunner.getState());
    mainRunner.interrupt();
}
Run Code Online (Sandbox Code Playgroud)