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
This is what I'm using nowadays if the test result is produced asynchronously.
public class TestUtil {
public static R await(Consumer> completer) {
return await(20, TimeUnit.SECONDS, completer);
}
public static R await(int time, TimeUnit unit, Consumer> completer) {
CompletableFuture f = new CompletableFuture<>();
completer.accept(f);
try {
return f.get(time, unit);
} catch (InterruptedException | TimeoutException e) {
throw new RuntimeException("Future timed out", e);
} catch (ExecutionException e) {
throw new RuntimeException("Future failed", e.getCause());
}
}
}
Using static imports, the test reads kinda nice. (note, in this example I'm starting a thread to illustrate the idea)
@Test
public void testAsync() {
String result = await(f -> {
new Thread(() -> f.complete("My Result")).start();
});
assertEquals("My Result", result);
}
If f.complete isn't called, the test will fail after a timeout. You can also use f.completeExceptionally to fail early.