-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncServiceTest.java
More file actions
71 lines (60 loc) · 2.17 KB
/
AsyncServiceTest.java
File metadata and controls
71 lines (60 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.example.testing.async;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AsyncServiceTest {
private static final AsyncService asyncService = new AsyncService();
@Nested
class WithoutAwaitility {
/**
* This test is flakey because it asserts on the result of some async
* processing, sometimes it might pass and other times it will fail.
*/
@Test
@Tag("failing")
void async_thing_is_done() {
asyncService.doSomethingAsync();
assertTrue(asyncService.isDone());
}
/**
* This test is less likely to flake because we've introduced a fixed sleep.
* Fine here because we *know* the maximum wait of the async code, but in
* the real world this won't always be possible.
* <p>
* Also, it can add a lot of unnecessary waiting to your tests.
*/
@Test
@SneakyThrows
void async_thing_is_done_wait() {
asyncService.doSomethingAsync();
Thread.sleep(10_000L);
assertTrue(asyncService.isDone());
}
}
@Nested
class WithAwaitility {
/**
* Awaitility gives us a flexible way of asserting on our async code.
* We could write something like this ourselves with a loop and sleeps, but
* this is much cleaner.
*/
@Test
void async_thing_is_done() {
asyncService.doSomethingAsync();
await().atMost(Duration.ofSeconds(10L))
.pollInterval(Duration.ofSeconds(1L))
.pollDelay(Duration.ofSeconds(1L))
.ignoreExceptions()
.untilAsserted(() -> {
var done = asyncService.isDone();
System.out.println("Is done: %b".formatted(done));
assertTrue(done);
});
}
}
}