Getting a TimerTask to run when using JUnit

John picture John · Nov 3, 2013 · Viewed 8.4k times · Source

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?

Answer

CtrlF picture CtrlF · Nov 8, 2013

You can do something like this:

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
}

The CountDownLatch#await() method will block the current thread until countDown() has been called at least the number of times specified at construction, in this case once. You can supply arguments to await() if you want to set a maximum amount of time to wait.

More information can be found here: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html