سؤال

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?

هل كانت مفيدة؟

المحلول 3

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

نصائح أخرى

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

JUnit is not really setup to run multithreaded code. When the main thread exits, it will stop all other Threads. In other words, if your thread scheduler doesn't context switch to the thread running the new TimerTask before returning from your @Test method, it will just kill that thread and exit the JVM, thus never executing your method.

You can either put a Thread.sleep(long) like Stefan suggested, or use a different design, possibly a ScheduledThreadPoolExecutor where you can awaitTermination with some timeout value.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top