[BAEL-6027] Add example for Awaitility and Thread.sleep comparison (#13450)

* Add example for Awaitility and Thread.sleep comparison

* Fix unit test method name and indentation.

* Use property in pom.xml for awaitility dependency version.

---------

Co-authored-by: Uhrin Attila <attila.uhrin@frontendart.com>
This commit is contained in:
AttilaUhrin 2023-02-18 04:04:25 +01:00 committed by GitHub
parent db2d8069e3
commit 4acdb03e61
3 changed files with 88 additions and 0 deletions

View File

@ -24,4 +24,16 @@
</resources> </resources>
</build> </build>
<properties>
<awaitility.version>4.2.0</awaitility.version>
</properties>
<dependencies>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -0,0 +1,35 @@
package com.baeldung.concurrent;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class RequestProcessor {
private Map<String, String> requestStatuses = new HashMap<>();
public String processRequest() {
String requestId = UUID.randomUUID().toString();
requestStatuses.put(requestId, "PROCESSING");
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule((() -> {
requestStatuses.put(requestId, "DONE");
}), getRandomNumberBetween(500, 2000), TimeUnit.MILLISECONDS);
return requestId;
}
public String getStatus(String requestId) {
return requestStatuses.get(requestId);
}
private int getRandomNumberBetween(int min, int max) {
Random random = new Random();
return random.nextInt(max - min) + min;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.concurrent;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("Request processor")
public class RequestProcessorUnitTest {
RequestProcessor requestProcessor = new RequestProcessor();
@Test
@DisplayName("Wait for completion using Thread.sleep")
void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
String requestId = requestProcessor.processRequest();
Thread.sleep(2000);
assertEquals("DONE", requestProcessor.getStatus(requestId));
}
@Test
@DisplayName("Wait for completion using Awaitility")
void whenWaitingWithAwaitility_thenStatusIsDone() {
String requestId = requestProcessor.processRequest();
Awaitility.await()
.atMost(2, TimeUnit.SECONDS)
.pollDelay(500, TimeUnit.MILLISECONDS)
.until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
assertEquals("DONE", requestProcessor.getStatus(requestId));
}
}