Video in progress
How do you check a STOMP endpoint with an integration test?
With @SpringBootTest(webEnvironment = RANDOM_PORT) a real server starts. You connect with WebSocketStompClient, subscribe to a topic, send a message, and wait for the reply with a timeout through a BlockingQueue or CompletableFuture.
📖 Answer
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ChatStompIT {
@LocalServerPort int port;
@Test
void messageIsBroadcast() throws Exception {
var client = new WebSocketStompClient(new StandardWebSocketClient());
client.setMessageConverter(new MappingJackson2MessageConverter());
StompSession session = client
.connectAsync("ws://localhost:" + port + "/ws", new StompSessionHandlerAdapter() {})
.get(5, TimeUnit.SECONDS);
BlockingQueue<ChatMessage> received = new LinkedBlockingQueue<>();
session.subscribe("/topic/chat", new StompFrameHandler() {
public Type getPayloadType(StompHeaders h) { return ChatMessage.class; }
public void handleFrame(StompHeaders h, Object p) { received.add((ChatMessage) p); }
});
Thread.sleep(200); // so the subscription reaches the server
session.send("/app/chat.send", new ChatMessage("ali", "salom"));
ChatMessage msg = received.poll(5, TimeUnit.SECONDS);
assertThat(msg).isNotNull();
assertThat(msg.text()).isEqualTo("salom");
}
}
A few practical nuances:
subscribeis asynchronous. If yousendright away, sometimes the message arrives before the subscription and the test becomes flaky. Instead ofsleep, it's cleaner to wait explicitly for the subscription to arrive: thereceiptheader andReceiptable.addReceiptTaskwork only if the broker returns aRECEIPTframe (the RabbitMQ relay does); don't rely on it with Spring's simple broker. The universal way is a bean in the test that listens forSessionSubscribeEventplus aCountDownLatch. Forreceiptyou also have to give the client asetTaskScheduler.- Never use an unbounded
take(): the test will hang. Always use a timeout. - If you need authentication, add the token to
CONNECTthrough theStompHeadersparameter ofconnectAsync. - You can unit test the controller logic separately; it's an ordinary method. The integration test checks that routing, prefixes, serialization and security are configured correctly.
Sign up to mark studied questions and save your progress.