Using Thread.sleep in a test is just generally a bad idea. It creates brittle tests that can fail unpredictably depending on
environment ("Passes on my machine!") or load. Don't rely on timing (use mocks) or use libraries such as Awaitility for asynchroneous
testing.
@Test
public void testDoTheThing(){
MyClass myClass = new MyClass();
myClass.doTheThing();
Thread.sleep(500); // Noncompliant
// assertions...
}
@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...
}
};
}