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:

  • subscribe is asynchronous. If you send right away, sometimes the message arrives before the subscription and the test becomes flaky. Instead of sleep, it's cleaner to wait explicitly for the subscription to arrive: the receipt header and Receiptable.addReceiptTask work only if the broker returns a RECEIPT frame (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 for SessionSubscribeEvent plus a CountDownLatch. For receipt you also have to give the client a setTaskScheduler.
  • Never use an unbounded take(): the test will hang. Always use a timeout.
  • If you need authentication, add the token to CONNECT through the StompHeaders parameter of connectAsync.
  • 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.