Skip to content

Commit 2b7db6e

Browse files
committed
Add tests for SSE heartbeat (ping) functionality
This commit adds test cases to verify the heartbeat (ping) feature in SseEmitter. The tests ensure that heartbeat messages are sent at the specified interval and that they stop after the emitter is completed. See: spring-projectsgh-33355
1 parent 28dbcb2 commit 2b7db6e

File tree

1 file changed

+39
-0
lines changed
  • spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation

1 file changed

+39
-0
lines changed

spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitterTests.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,45 @@ void sendEventFullWithTwoDataLinesInTheMiddle() throws Exception {
137137
this.handler.assertWriteCount(1);
138138
}
139139

140+
@Test
141+
void heartbeatIsSent() throws Exception {
142+
this.emitter = new SseEmitter(0L, 100L);
143+
this.emitter.initialize(this.handler);
144+
Thread.sleep(250);
145+
int heartbeatCount = 0;
146+
for (int i = 0; i < this.handler.objects.size(); i++) {
147+
Object data = this.handler.objects.get(i);
148+
if (data.equals(":heartbeat\n\n")) {
149+
heartbeatCount++;
150+
}
151+
}
152+
assertThat(heartbeatCount).isGreaterThanOrEqualTo(2);
153+
}
154+
155+
@Test
156+
void heartbeatStopsAfterCompletion() throws Exception {
157+
this.emitter = new SseEmitter(0L, 100L);
158+
this.emitter.initialize(this.handler);
159+
160+
Thread.sleep(150);
161+
this.emitter.complete();
162+
163+
int heartbeatCountBeforeCompletion = 0;
164+
for (Object data : this.handler.objects) {
165+
if (data.equals(":heartbeat\n\n")) {
166+
heartbeatCountBeforeCompletion++;
167+
}
168+
}
169+
Thread.sleep(150);
170+
int totalHeartbeatCount = 0;
171+
for (Object data : this.handler.objects) {
172+
if (data.equals(":heartbeat\n\n")) {
173+
totalHeartbeatCount++;
174+
}
175+
}
176+
assertThat(totalHeartbeatCount).isEqualTo(heartbeatCountBeforeCompletion);
177+
}
178+
140179

141180
private static class TestHandler implements ResponseBodyEmitter.Handler {
142181

0 commit comments

Comments
 (0)