rspec/rules/S2925/java/rule.adoc

74 lines
1.9 KiB
Plaintext

== Why is this an issue?
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
[source,java,diff-id=1,diff-type=noncompliant]
----
@Test
public void testDoTheThing(){
MyClass myClass = new MyClass();
myClass.doTheThing();
Thread.sleep(500); // Noncompliant
// assertions...
}
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@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...
}
};
}
----
== Resources
=== Documentation
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html[Oracle SE 20 - Thread]
* http://www.awaitility.org/[Awaitility]
=== Articles & blog posts
* https://www.baeldung.com/java-thread-sleep-vs-awaitility-await[Baeldung - Thread.sleep() vs Awaitility.await()]
* https://www.baeldung.com/awaitility-testing[Baeldung - Awaitility testing]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this use of "Thread.sleep()".
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]