In asynchronous testing, the test code is written in a way that allows it to wait for the asynchronous operation to complete before continuing with
the test.
Using Thread.sleep
in this case can cause flaky tests, slow test execution, and inaccurate test results. It creates brittle tests that
can fail unpredictably depending on the environment or load.
Use mocks or libraries such as Awaitility
instead. These tools provide features such as timeouts, assertions, and error handling to
make it easier to write and manage asynchronous tests.
Noncompliant code example
@Test
public void testDoTheThing(){
MyClass myClass = new MyClass();
myClass.doTheThing();
Thread.sleep(500); // Noncompliant
// assertions...
}
Compliant solution
@Test
public void testDoTheThing(){
MyClass myClass = new MyClass();
myClass.doTheThing();
await().atMost(2, Duration.SECONDS).until(didTheThing()); // Compliant
// assertions...
}
private Callable<Boolean> didTheThing() {
return new Callable<Boolean>() {
public Boolean call() throws Exception {
// check the condition that must be fulfilled...
}
};
}