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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With