Skip to content

Commit 37437d0

Browse files
mirogaudiAndrey Strukov
andauthored
chore(tests): Fix tests: Use Awaitility.await() instead of Thread.sleep() (#4470)
Co-authored-by: Andrey Strukov <[email protected]>
1 parent a98da37 commit 37437d0

File tree

6 files changed

+88
-92
lines changed

6 files changed

+88
-92
lines changed

spring-boot-admin-client/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,5 +84,10 @@
8484
<artifactId>wiremock-standalone</artifactId>
8585
<scope>test</scope>
8686
</dependency>
87+
<dependency>
88+
<groupId>org.awaitility</groupId>
89+
<artifactId>awaitility</artifactId>
90+
<scope>test</scope>
91+
</dependency>
8792
</dependencies>
8893
</project>

spring-boot-admin-client/src/test/java/de/codecentric/boot/admin/client/AbstractClientApplicationTest.java

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import java.net.InetAddress;
2020
import java.net.UnknownHostException;
21+
import java.time.Duration;
2122
import java.util.Arrays;
2223
import java.util.concurrent.CountDownLatch;
2324
import java.util.stream.Stream;
@@ -47,6 +48,7 @@
4748
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
4849
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
4950
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
51+
import static org.awaitility.Awaitility.await;
5052

5153
public abstract class AbstractClientApplicationTest {
5254

@@ -59,7 +61,7 @@ public abstract class AbstractClientApplicationTest {
5961

6062
private static final CountDownLatch cdl = new CountDownLatch(1);
6163

62-
protected void setUp(WebApplicationType type) throws Exception {
64+
protected void setUp(WebApplicationType type) {
6365
setUpWiremock();
6466
setUpApplication(type);
6567
}
@@ -100,8 +102,6 @@ void tearDown() {
100102
public void test_context() throws InterruptedException, UnknownHostException {
101103
setUpApplicationContext();
102104

103-
cdl.await();
104-
Thread.sleep(2500);
105105
String hostName = InetAddress.getLocalHost().getCanonicalHostName();
106106
String serviceHost = "http://" + hostName + ":" + getServerPort();
107107
String managementHost = "http://" + hostName + ":" + getManagementPort();
@@ -113,15 +113,14 @@ public void test_context() throws InterruptedException, UnknownHostException {
113113
.withRequestBody(matchingJsonPath("$.serviceUrl", equalTo(serviceHost + "/")))
114114
.withRequestBody(matchingJsonPath("$.metadata.startup", matching(".+")));
115115

116-
wireMock.verify(request);
116+
cdl.await();
117+
await().atMost(Duration.ofMillis(2500)).untilAsserted(() -> wireMock.verify(request));
117118
}
118119

119120
@Test
120121
public void test_context_with_snake_case() throws InterruptedException, UnknownHostException {
121122
setUpApplicationContext("--spring.jackson.property-naming-strategy=SNAKE_CASE");
122123

123-
cdl.await();
124-
Thread.sleep(2500);
125124
String hostName = InetAddress.getLocalHost().getCanonicalHostName();
126125
String serviceHost = "http://" + hostName + ":" + getServerPort();
127126
String managementHost = "http://" + hostName + ":" + getManagementPort();
@@ -133,7 +132,8 @@ public void test_context_with_snake_case() throws InterruptedException, UnknownH
133132
.withRequestBody(matchingJsonPath("$.service_url", equalTo(serviceHost + "/")))
134133
.withRequestBody(matchingJsonPath("$.metadata.startup", matching(".+")));
135134

136-
wireMock.verify(request);
135+
cdl.await();
136+
await().atMost(Duration.ofMillis(2500)).untilAsserted(() -> wireMock.verify(request));
137137
}
138138

139139
private int getServerPort() {
@@ -154,14 +154,7 @@ public static class TestClientApplication {
154154
@EventListener
155155
public void ping(ApplicationReadyEvent ev) {
156156
new Thread(() -> {
157-
try {
158-
while (registrator.getRegisteredId() == null) {
159-
Thread.sleep(500);
160-
}
161-
}
162-
catch (InterruptedException ex) {
163-
Thread.interrupted();
164-
}
157+
await().atMost(Duration.ofMillis(500)).until(() -> registrator.getRegisteredId() != null);
165158
cdl.countDown();
166159
}).start();
167160
}

spring-boot-admin-server/src/test/java/de/codecentric/boot/admin/server/notify/RemindingNotifierTest.java

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020

2121
import org.junit.jupiter.api.BeforeEach;
2222
import org.junit.jupiter.api.Test;
23+
import org.junit.jupiter.params.ParameterizedTest;
24+
import org.junit.jupiter.params.provider.NullSource;
2325
import reactor.core.publisher.Flux;
2426
import reactor.core.publisher.Mono;
2527
import reactor.test.StepVerifier;
@@ -38,11 +40,12 @@
3840

3941
import static org.assertj.core.api.Assertions.assertThat;
4042
import static org.assertj.core.api.Assertions.assertThatThrownBy;
43+
import static org.awaitility.Awaitility.await;
4144
import static org.mockito.ArgumentMatchers.any;
4245
import static org.mockito.Mockito.mock;
4346
import static org.mockito.Mockito.when;
4447

45-
public class RemindingNotifierTest {
48+
class RemindingNotifierTest {
4649

4750
private static final Instance instance1 = Instance.create(InstanceId.of("id-1"))
4851
.register(Registration.create("App", "http://health").build())
@@ -71,38 +74,40 @@ public class RemindingNotifierTest {
7174
private InstanceRepository repository;
7275

7376
@BeforeEach
74-
public void setUp() {
77+
void setUp() {
7578
this.repository = mock(InstanceRepository.class);
7679
when(this.repository.find(any())).thenReturn(Mono.empty());
7780
when(this.repository.find(instance1.getId())).thenReturn(Mono.just(instance1));
7881
when(this.repository.find(instance2.getId())).thenReturn(Mono.just(instance2));
7982
}
8083

81-
@Test
82-
public void should_throw_on_invalid_ctor() {
83-
assertThatThrownBy(() -> new CompositeNotifier(null)).isInstanceOf(IllegalArgumentException.class);
84+
@ParameterizedTest
85+
@NullSource
86+
void should_throw_on_invalid_ctor(Iterable<Notifier> delegates) {
87+
assertThatThrownBy(() -> new CompositeNotifier(delegates)).isInstanceOf(IllegalArgumentException.class);
8488
}
8589

8690
@Test
87-
public void should_remind_only_down_events() throws InterruptedException {
91+
void should_remind_only_down_events() {
8892
TestNotifier notifier = new TestNotifier();
8993
RemindingNotifier reminder = new RemindingNotifier(notifier, this.repository);
9094
reminder.setReminderPeriod(Duration.ZERO);
9195

9296
StepVerifier.create(reminder.notify(appDown)).verifyComplete();
9397
StepVerifier.create(reminder.notify(appEndpointsDiscovered)).verifyComplete();
9498
StepVerifier.create(reminder.notify(otherAppUp)).verifyComplete();
95-
Thread.sleep(10);
96-
StepVerifier.create(reminder.sendReminders()).verifyComplete();
97-
Thread.sleep(10);
98-
StepVerifier.create(reminder.sendReminders()).verifyComplete();
99+
100+
await().pollDelay(Duration.ofMillis(10))
101+
.untilAsserted(() -> StepVerifier.create(reminder.sendReminders()).verifyComplete());
102+
await().pollDelay(Duration.ofMillis(10))
103+
.untilAsserted(() -> StepVerifier.create(reminder.sendReminders()).verifyComplete());
99104

100105
assertThat(notifier.getEvents()).containsExactlyInAnyOrder(appDown, appEndpointsDiscovered, otherAppUp, appDown,
101106
appDown);
102107
}
103108

104109
@Test
105-
public void should_not_remind_remind_after_up() {
110+
void should_not_remind_remind_after_up() {
106111
TestNotifier notifier = new TestNotifier();
107112
RemindingNotifier reminder = new RemindingNotifier(notifier, this.repository);
108113
reminder.setReminderPeriod(Duration.ZERO);
@@ -115,7 +120,7 @@ public void should_not_remind_remind_after_up() {
115120
}
116121

117122
@Test
118-
public void should_not_remind_remind_after_deregister() {
123+
void should_not_remind_remind_after_deregister() {
119124
TestNotifier notifier = new TestNotifier();
120125
RemindingNotifier reminder = new RemindingNotifier(notifier, this.repository);
121126
reminder.setReminderPeriod(Duration.ZERO);
@@ -128,7 +133,7 @@ public void should_not_remind_remind_after_deregister() {
128133
}
129134

130135
@Test
131-
public void should_not_remind_remind_before_period_ends() {
136+
void should_not_remind_remind_before_period_ends() {
132137
TestNotifier notifier = new TestNotifier();
133138
RemindingNotifier reminder = new RemindingNotifier(notifier, this.repository);
134139
reminder.setReminderPeriod(Duration.ofHours(24));
@@ -140,7 +145,7 @@ public void should_not_remind_remind_before_period_ends() {
140145
}
141146

142147
@Test
143-
public void should_resubscribe_after_error() {
148+
void should_resubscribe_after_error() {
144149
TestPublisher<InstanceEvent> eventPublisher = TestPublisher.create();
145150

146151
Flux<InstanceEvent> emittedNotifications = Flux.create((emitter) -> {

spring-boot-admin-server/src/test/java/de/codecentric/boot/admin/server/services/InfoUpdateTriggerTest.java

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
import static org.mockito.Mockito.verify;
4646
import static org.mockito.Mockito.when;
4747

48-
public class InfoUpdateTriggerTest {
48+
class InfoUpdateTriggerTest {
4949

5050
private final Instance instance = Instance.create(InstanceId.of("id-1"))
5151
.register(Registration.create("foo", "http://health-1").build());
@@ -57,7 +57,7 @@ public class InfoUpdateTriggerTest {
5757
private InfoUpdateTrigger trigger;
5858

5959
@BeforeEach
60-
public void setUp() throws Exception {
60+
void setUp() {
6161
when(this.updater.updateInfo(any(InstanceId.class))).thenReturn(Mono.empty());
6262

6363
this.trigger = new InfoUpdateTrigger(this.updater, this.events.flux(), Duration.ofMinutes(5),
@@ -67,7 +67,7 @@ public void setUp() throws Exception {
6767
}
6868

6969
@Test
70-
public void should_start_and_stop_monitor() throws Exception {
70+
void should_start_and_stop_monitor() {
7171
// given
7272
this.trigger.stop();
7373
this.trigger.setInterval(Duration.ofMillis(10));
@@ -77,33 +77,30 @@ public void should_start_and_stop_monitor() throws Exception {
7777

7878
this.events.next(
7979
new InstanceStatusChangedEvent(this.instance.getId(), this.instance.getVersion(), StatusInfo.ofDown()));
80-
81-
Thread.sleep(50L);
8280
// then it should start updating one time for registration and at least once for
8381
// monitor
84-
verify(this.updater, atLeast(2)).updateInfo(this.instance.getId());
82+
await().atMost(Duration.ofMillis(50))
83+
.pollInterval(Duration.ofMillis(10))
84+
.untilAsserted(() -> verify(this.updater, atLeast(2)).updateInfo(this.instance.getId()));
8585

8686
// given long lifetime
8787
this.trigger.setLifetime(Duration.ofSeconds(10));
88-
Thread.sleep(50L);
8988
clearInvocations(this.updater);
90-
// when the lifetime is not expired
91-
Thread.sleep(50L);
92-
// should never update
93-
verify(this.updater, never()).updateInfo(any(InstanceId.class));
89+
// when the lifetime is not expired should never update
90+
await().pollDelay(Duration.ofMillis(50))
91+
.untilAsserted(() -> verify(this.updater, never()).updateInfo(any(InstanceId.class)));
9492

95-
// when trigger ist destroyed
9693
this.trigger.setLifetime(Duration.ofMillis(10));
9794
this.trigger.stop();
9895
clearInvocations(this.updater);
99-
Thread.sleep(15L);
10096

101-
// it should stop updating
102-
verify(this.updater, never()).updateInfo(any(InstanceId.class));
97+
// when trigger ist destroyed it should stop updating
98+
await().pollDelay(Duration.ofMillis(15))
99+
.untilAsserted(() -> verify(this.updater, never()).updateInfo(any(InstanceId.class)));
103100
}
104101

105102
@Test
106-
public void should_not_update_when_stopped() {
103+
void should_not_update_when_stopped() {
107104
// when registered event is emitted but the trigger has been stopped
108105
this.trigger.stop();
109106
clearInvocations(this.updater);
@@ -114,7 +111,7 @@ public void should_not_update_when_stopped() {
114111
}
115112

116113
@Test
117-
public void should_update_on_endpoints_detectes_event() {
114+
void should_update_on_endpoints_detects_event() {
118115
// when registered event is emitted
119116
this.events.next(new InstanceEndpointsDetectedEvent(this.instance.getId(), this.instance.getVersion(),
120117
this.instance.getEndpoints()));
@@ -123,7 +120,7 @@ public void should_update_on_endpoints_detectes_event() {
123120
}
124121

125122
@Test
126-
public void should_update_on_status_changed_event() {
123+
void should_update_on_status_changed_event() {
127124
// when registered event is emitted
128125
this.events.next(
129126
new InstanceStatusChangedEvent(this.instance.getId(), this.instance.getVersion(), StatusInfo.ofDown()));
@@ -132,7 +129,7 @@ public void should_update_on_status_changed_event() {
132129
}
133130

134131
@Test
135-
public void should_update_on_instance_registration_update_event() {
132+
void should_update_on_instance_registration_update_event() {
136133
// when registered event is emitted
137134
this.events.next(new InstanceRegistrationUpdatedEvent(this.instance.getId(), this.instance.getVersion(),
138135
this.instance.getRegistration()));
@@ -141,15 +138,15 @@ public void should_update_on_instance_registration_update_event() {
141138
}
142139

143140
@Test
144-
public void should_not_update_on_non_relevant_event() {
141+
void should_not_update_on_non_relevant_event() {
145142
// when some non-registered event is emitted
146143
this.events.next(new InstanceInfoChangedEvent(this.instance.getId(), this.instance.getVersion(), Info.empty()));
147144
// then should not update
148145
verify(this.updater, never()).updateInfo(this.instance.getId());
149146
}
150147

151148
@Test
152-
public void should_continue_update_after_error() throws InterruptedException {
149+
void should_continue_update_after_error() {
153150
// when status-change event is emitted and an error is emitted
154151
when(this.updater.updateInfo(any())).thenReturn(Mono.error(IllegalStateException::new))
155152
.thenReturn(Mono.empty());

0 commit comments

Comments
 (0)