Skip to content

WebSockets Overview

WireMock provides built-in support for mocking WebSocket connections, enabling you to test real-time, bidirectional communication in your applications without requiring a real WebSocket server.

WebSocket support in WireMock works as follows:

  1. Connection: Clients connect to WireMock using the WebSocket protocol (ws:// or wss://) on any URL path
  2. Channel creation: Each connection creates a message channel, identified by the initiating HTTP upgrade request
  3. Message handling: Incoming messages are matched against message stub mappings
  4. Response delivery: When a stub matches, configured actions (like sending responses) are executed
  5. Journaling: All messages are recorded in the message journal for verification

WebSocket clients can connect to any path on the WireMock server:

// Example WebSocket client connection
WebSocketClient client = new WebSocketClient();
client.connect("ws://localhost:8080/my-websocket-endpoint");

The URL path used for the connection can be matched in your stubs, allowing you to create different behaviors for different endpoints.

Channels are identified by the HTTP request that initiated the WebSocket upgrade. This allows you to:

  • Match stubs to specific WebSocket endpoints based on URL patterns
  • Match based on headers or other request attributes
  • Broadcast messages to channels matching specific criteria
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;
// Stub that only applies to a specific WebSocket path
messageStubFor(
message()
.withName("VIP channel stub")
.onWebsocketChannelFromRequestMatching(
newRequestPattern().withUrl("/vip-channel"))
.withBody(equalTo("request"))
.willTriggerActions(
sendMessage("VIP response").onOriginatingChannel()));

WireMock WebSocket support handles both text and binary messages:

Most WebSocket communication uses text messages, typically JSON-formatted:

messageStubFor(
message()
.withBody(matchingJsonPath("$.action", equalTo("subscribe")))
.willTriggerActions(
sendMessage("{\"status\": \"subscribed\"}")
.onOriginatingChannel()));

Binary messages are also supported for protocols that require binary data transfer.

One of the powerful features of WebSocket mocking is the ability to broadcast messages to multiple connected clients:

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;
// When any client sends "broadcast", send a message to all clients
// connected to paths matching /broadcast/*
messageStubFor(
message()
.withName("Broadcast stub")
.withBody(equalTo("broadcast"))
.willTriggerActions(
sendMessage("broadcast message")
.onChannelsMatching(
newRequestPattern()
.withUrl(urlPathMatching("/broadcast/.*")))));

WebSocket connections can be tuned via configuration options:

OptionDefaultDescription
webSocketIdleTimeout300000ms (5 min)Idle timeout before connection is closed
webSocketMaxTextMessageSize10485760 bytes (10MB)Maximum size of text messages
webSocketMaxBinaryMessageSize10485760 bytes (10MB)Maximum size of binary messages

See Configuration for details on setting these options.

WireMock manages WebSocket connection lifecycle automatically:

  1. Connect: Client initiates WebSocket handshake
  2. Open: Connection established, channel created
  3. Messages: Bidirectional message exchange
  4. Close: Connection terminated, channel removed

You can list all active WebSocket channels via the Admin API:

Terminal window
curl http://localhost:8080/__admin/channels

Response:

{
"channels": [
{
"id": "abc123",
"type": "websocket",
"initiatingRequest": {
"url": "/my-websocket",
"method": "GET"
}
}
]
}

Here’s a complete example of testing WebSocket communication:

@Test
void testWebSocketEcho() {
// Set up the stub
messageStubFor(
message()
.withName("Echo stub")
.withBody(matching(".*"))
.willTriggerActions(
sendMessage("Echo: {{message.body}}")
.onOriginatingChannel()));
// Connect a WebSocket client
WebSocketClient client = new WebSocketClient();
client.connect("ws://localhost:" + wireMockServer.port() + "/echo");
// Send a message and verify the response
String response = client.sendMessageAndWaitForResponse("Hello, WebSocket!");
assertThat(response, is("Echo: Hello, WebSocket!"));
// Verify the message was received
verifyMessageEvent(
messagePattern()
.withBody(equalTo("Hello, WebSocket!"))
.build());
}