How do you test methods that fire asynchronous processes with JUnit?
I don\'t know how to make my test wait for the process to end (it is not exactly a unit test, it
There's nothing inherently wrong with testing threaded/async code, particularly if threading is the point of the code you're testing. The general approach to testing this stuff is to:
But that's a lot of boilerplate for one test. A better/simpler approach is to just use ConcurrentUnit:
final Waiter waiter = new Waiter();
new Thread(() -> {
doSomeWork();
waiter.assertTrue(true);
waiter.resume();
}).start();
// Wait for resume() to be called
waiter.await(1000);
The benefit of this over the CountdownLatch approach is that it's less verbose since assertion failures that occur in any thread are properly reported to the main thread, meaning the test fails when it should. A writeup that compares the CountdownLatch approach to ConcurrentUnit is here.
I also wrote a blog post on the topic for those who want to learn a bit more detail.