如何使用junit测试阻塞方法

时间:2015-05-22 18:51:55

标签: java unit-testing junit

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

 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);
}

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

public class ApplicationLauncherTest extends TestCase {


    public void testMain() throws Exception {
        ApplicationLauncher launcher = new ApplicationLauncher();
    }
}

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:-1)

Bwire的回答是一个好方法,但我高度建议不要 一个人在单元测试中使用Thread.sleep()来验证某些情况。正确的时机是不可能的:

  • 如果它太短,你会得到很多假结果(随机失败,yay)
  • 如果时间过长,最终会导致测试速度变慢。不要低估这一点。

那么,答案是什么?任何时候你需要“睡觉”来测试一些东西,而不是“等待”它是真的(不断检查)。这样:

  • 一旦条件成立,你的程序就会恢复 - 没有浪费时间。
  • 您可以将此“等待”的超时设置为一个疯狂的大值,以避免随机失败。

以下是Bware自我回应的修改版本......

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

    mainRunner.start();

    expectToBlock(mainRunner, 30, TimeUnit.SECONDS);

    mainRunner.interrupt();
}

private static void expectToBlock(Thread thread, long waitCount, TimeUnit waitUnits) {
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < waitUnits.toMillis(waitCount)) {
        if (thread.getState() == Thread.State.WAITING) {
            return;
        }
        Thread.sleep(50); // Don't hog the CPU
    }
    Assert.fail("Timed out while waiting for thread to block");
}
相关问题