Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a TimerTask to run when using JUnit

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?

like image 709
John Avatar asked Nov 03 '13 04:11

John


People also ask

How do I run JUnit tests automatically?

To run JUnit 5 tests from Java code, we'll set up an instance of LauncherDiscoveryRequest. It uses a builder class where we must set package selectors and testing class name filters, to get all test classes that we want to run.

How do you schedule a Timer in Java?

Java Timer schedule() methodThe schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.


1 Answers

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

like image 51
CtrlF Avatar answered Oct 18 '22 21:10

CtrlF