Skip to main content
L3gitUI · API · MOBILE TEST AUTOMATION
[ PRODUCT ][ PRICING ][ DOCS ][ VERIFIED ][ REGULATED ][ COMPARE ][ ACCOUNT ] Start Free Trial

/// Resources / WebSocket

WebSocket testing with Cucumber steps in Java: connect, send, expect, close on the JDK client

Published 2026-11-286 min readL3git Development

A WebSocket test has the same shape as a Kafka test: you send something, and the assertion is a frame arrives within a timeout. The difference is that you need no library at all. java.net.http.WebSocket has shipped in the JDK since 11, and about sixty lines on top of it give you four readable Gherkin steps and a client that does not drop the message that arrived before you asked for it.

What the scenario should read like

Scenario: The price feed answers a subscription
  Given I connect to the websocket "wss://feed.example.com/quotes"
  When I send this websocket message:
    """
    { "subscribe": "ACME" }
    """
  Then I should receive a websocket message containing "\"symbol\":\"ACME\""
  And I close the websocket

Connect takes a ws:// or wss:// URL, send takes a doc string, expect takes a substring and (in the step definition) a timeout, close is close. The TLS handshake, fragment reassembly and the inbound buffer live in a support class.

The client: buffer first, assert later

The mistake every first attempt makes is registering the listener in the expect step. By then the reply has often already arrived and been discarded. The listener is attached at connect time and every complete text message goes into a queue; expect drains the queue:

public class WsClient {
    private WebSocket ws;
    private final BlockingQueue<String> inbox = new LinkedBlockingQueue<>();
    private final StringBuilder partial = new StringBuilder();

    public void connect(String url) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        ws = client.newWebSocketBuilder()
                .connectTimeout(Duration.ofSeconds(15))
                .buildAsync(URI.create(url), new WebSocket.Listener() {
                    @Override
                    public CompletionStage<?> onText(WebSocket socket, CharSequence data, boolean last) {
                        partial.append(data);
                        if (last) { inbox.offer(partial.toString()); partial.setLength(0); }
                        socket.request(1);
                        return null;
                    }
                })
                .get(20, TimeUnit.SECONDS);
    }

    public void send(String message) {
        require();
        ws.sendText(message, true).join();
    }
}

Two details are easy to miss. The JDK delivers large messages as several onText calls with last == false until the final fragment, so the fragments are joined before the message is queued; a substring assertion against a half message is a flaky test. And socket.request(1) is what asks for the next frame: forget it and you receive exactly one message, ever.

Expect: poll the inbox until a match or the deadline

public String expect(String contains, long timeoutMs) throws InterruptedException {
    require();
    long end = System.currentTimeMillis() + timeoutMs;
    while (true) {
        long remaining = end - System.currentTimeMillis();
        if (remaining <= 0) { break; }
        String msg = inbox.poll(remaining, TimeUnit.MILLISECONDS);
        if (msg == null) { break; }
        if (contains == null || contains.isEmpty() || msg.contains(contains)) { return msg; }
    }
    throw new AssertionError("WebSocket: no message"
            + (contains == null || contains.isEmpty() ? "" : " containing \"" + contains + "\"")
            + " within " + timeoutMs + "ms");
}

Non-matching messages are consumed and skipped, so a heartbeat or a welcome frame ahead of the one you want does not fail the step. The deadline is absolute, not per message, so a chatty server cannot keep the step alive forever. A blank contains accepts any message, which is the right assertion for something came back.

The step definitions

private final com.example.support.WsClient ws = new com.example.support.WsClient();

@Given("I connect to the websocket {string}")
public void connectWs(String url) throws Exception { ws.connect(url); }

@When("I send this websocket message:")
public void sendWs(String message) { ws.send(message); }

@Then("I should receive a websocket message containing {string}")
public void expectWs(String contains) throws Exception { ws.expect(contains, 5000); }

@When("I close the websocket")
public void closeWs() { ws.close(); }

One WsClient per step class means one connection per scenario, which is what you want: Cucumber creates a fresh step instance per scenario, so a leaked connection from one scenario cannot feed frames into the next. Close sends a normal closure (1000) with a reason and swallows any error, because a server that already hung up is not a test failure.

What this does not do

In L3git these are the four WebSocket entries under the non-REST step button in the API tab: connect (URL), send (message), expect (contains, timeout ms) and close. The recorder marks them runs in the generated project rather than replaying them live; generate, then mvn test. The same shape covers Kafka and gRPC; the setup walkthrough is guide 10 and the full protocol list is on the API testing tool page.

Questions

How do I try it without a server of my own?

Connect to wss://ws.postman-echo.com/raw, send ping-123 and expect ping-123: the echo proves the connect, send and buffered expect all work. Offline, a ten-line Node echo server on ws://localhost:8080 does the same job.

Can I assert on a JSON field instead of a substring?

expect returns the matched message. Call it from a custom script step, parse the string with the JSON library already in the project, and assert on the path. The substring match is the fast first check.

Why not just use REST Assured or OkHttp for this?

REST Assured has no WebSocket support. OkHttp and Tyrus work but add a dependency and a second client lifecycle to a project that already has the JDK one. Nothing here needs more than java.net.http, so the pom stays unchanged.

Try it: 14-day trial, no card More articles