Java Async testing

A Java Spring Boot powered REST Api has operations, which require minutes to finish, because of multiple HTTP connections and database queries with lots of data. These tasks are executed Asynchronously. 
The functionality needs to be tested in the integration tests (using less data, so the operation runs in seconds). Now we use Thread.sleep(…) and the tests take 10minutes to finish every time, while we see the operations finished sometimes for 2-3 seconds and the overall required time would be 5minutes. Bu we also observe flakey tests from time to time, because the operations take 100ms more than out waiting time.
 How can we test waiting time that is close to the real waiting time and remove the cause of the flakey tests?
2 answers

This one is the BEST answer!

Usually Mockito provides methods with timeout,
verify(…, timeout(…). But often it is not useful.
Thread.sleep() is a bad practise and may not work in some situations. Also it waits concrete amount of time (e.g 3000ms) and will always wait this interval, even if the operation took 300ms.

A nice solution to the problem is using the test dependency Awaitility.
It is extremely easy to use, has a fluent API, polls regularly and is configurable, so every test can be optimised.
The idea behind it, is that it polls every 100ms (by default, but configurable) and after 10sec (also by default and configurable) it announce the test failed if the condition is not met.

await()
.atLeast(1, SECONDS)
.atMost(5, SECONDS)
.until(imageInCdnIsDeleted(imageUrl));

So, instead of waiting every time 10 minutes for test to finish, because of the sleep time, the suite will finish for the (near) max time required for the operations. For example it may finish for 3.5minutes, but also for 8minutes.

Comments

I did not know Awaitility before.
Thanks for demonstrating this useful tool and a relateable scenario where it would be helpful!
Also the use and demonstration of it's configuration parameters was shown perfectly!

Marian Berendes - Mon, 12/10/2018 - 09:54 :::

I knew about Mockito before but Awaitility seems like a much better option. Thanks for sharing!

Angelos Arampatzis - Mon, 12/10/2018 - 14:10 :::

please delete