10

I have a function that looks like this:

private Timer timer = new Timer();

private void doSomething() {
    timer.schedule(new TimerTask() {
        public void run() {
            doSomethingElse();
        }
    },
    (1000));
}

I'm trying to write JUnit tests for my code, and they are not behaving as expected when testing this code in particular. By using EclEmma, I'm able to see that my tests never touched the doSomethingElse() function.

How do I write tests in JUnit that will wait long enough for the TimerTask to finish before continuing with the test?

4

3 回答 3

10

你可以这样做:

private Timer timer = new Timer();

private void doSomething() {
    final CountDownLatch latch = new CountDownLatch(1);

    timer.schedule(new TimerTask() {
        public void run() {
            doSomethingElse();
            latch.countDown();
        }
    },
    (1000));

    latch.await();
    // check results
}

CountDownLatch#await()方法将阻塞当前线程,直到countDown()至少被调用了构造时指定的次数,在本例中为一次。await()如果要设置最大等待时间,可以提供参数。

更多信息可以在这里找到:http: //docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html

于 2013-11-08T00:27:00.733 回答
5

JUnit 并没有真正设置为运行多线程代码。当主线程退出时,它将停止所有其他线程。换句话说,如果您的线程调度程序TimerTask在从您的@Test方法返回之前没有上下文切换到运行 new 的线程,它只会杀死该线程并退出 JVM,因此永远不会执行您的方法。

您可以Thread.sleep(long)像 Stefan 建议的那样放置一个,或者使用不同的设计,可能是ScheduledThreadPoolExecutor您可以awaitTermination使用一些超时值的地方。

于 2013-11-03T13:07:18.613 回答
-2

您可以Thread.sleep(1000)在测试中使用。

于 2013-11-03T07:11:58.537 回答