Search code examples
javajunittimertaskjunit3

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?


Solution

  • You may use Thread.sleep(1000) in your test.