WebSocket endpoint test client
Learn how to test a WebSocket endpoint with a real client, why oneshot cannot do the handshake, and how to assert echo round trips and authenticated upgrades
A WebSocket endpoint is not a request and a response. It is a conversation: a handshake that upgrades an HTTP connection, then messages flowing both ways on the open socket for as long as either side wants. The oneshot helper from the earlier pages cannot test that, because it sends one request and returns one response, and there is no socket left open to talk on. A WebSocket test needs a real server listening on a real port, and a real client that connects, sends, and listens. This page builds both.
Where This Fits
The tests so far sent one HTTP request and checked one HTTP response. This page is the first test that cannot work that way, because the thing under test is a connection, not a call. The endpoint is the echo server from the WebSockets chapter: it takes a WebSocketUpgrade, and every text or binary message it receives, it sends straight back. The test connects to it with a client, sends a message, and checks the echo comes back unchanged.
Think of a walkie-talkie check. One radio is the server, the other is the test client, and the test is pressing the button, saying a word, and listening for the same word to come back. A letter in the post cannot do that check, because the letter is one way and finished when it arrives. The WebSocket needs both radios on, at the same time, on the same channel.
The Smallest Working Version
The test starts a real server on a random port, connects with tokio-tungstenite, sends one message, and asserts the reply. The server is the echo handler from the WebSockets chapter, and the client is tokio-tungstenite version 0.30, the async WebSocket client built on tungstenite.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
futures-util = "0.3"
[dev-dependencies]
tokio-tungstenite = "0.30"
The ws feature on axum turns on the WebSocket support, including the WebSocketUpgrade extractor and the WebSocket type. Without it, those names do not exist. The futures-util dependency provides the SinkExt and StreamExt traits, which add the send and next methods the test calls on the socket. tokio-tungstenite is a dev-dependency, because only the tests use it. The server never needs a WebSocket client.
use axum::{
Router,
extract::ws::{Message, WebSocket, WebSocketUpgrade},
response::Response,
routing::get,
};
async fn ws_echo(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(|socket| async move {
echo_loop(socket).await;
})
}
async fn echo_loop(mut socket: WebSocket) {
while let Some(result) = socket.recv().await {
let Ok(message) = result else { return };
match message {
Message::Text(_) | Message::Binary(_) => {
if socket.send(message).await.is_err() {
return;
}
}
Message::Close(_) => return,
_ => {}
}
}
}
pub fn ws_app() -> Router {
Router::new().route("/ws", get(ws_echo))
}
The handler takes the upgrade extractor and hands the socket to on_upgrade, which runs the given future once the handshake completes. The loop receives messages one at a time. A text or binary message is sent straight back, unchanged, which is the echo. A close message ends the loop, and any other message, like a ping or a pong, is ignored. The Message type here is axum 0.8's, and its variants carry their payloads as Text(Utf8Bytes), Binary(Bytes), Ping(Bytes), Pong(Bytes), and Close(Option<CloseFrame>). The text payload is Utf8Bytes, a string type that guarantees valid UTF-8, and the binary payload is Bytes, a reference-counted byte buffer.
The test starts the server and connects:
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{connect_async, tungstenite::Message};
async fn start_server() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, axum_project::ws_app()).await.unwrap();
});
format!("ws://{addr}")
}
#[tokio::test]
async fn websocket_echo_round_trip_over_a_real_socket() {
let base = start_server().await;
let (mut ws, response) = connect_async(format!("{base}/ws")).await.unwrap();
assert_eq!(response.status(), 101);
ws.send(Message::Text("hello".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("hello".into()));
ws.close(None).await.unwrap();
}
Run it with:
cargo test --test ws_test
The test passes, and it proves the whole chain: the server started, the handshake upgraded the connection, a message went out, and the same message came back.
Working Setup:
If the echo test passes, the server, the handshake, and the client all work. The 101 status is the handshake succeeding, and the equal messages are the echo working. A failure before the first send means the server or the handshake is broken, and a failure on the reply means the echo loop is broken.
Why oneshot Cannot Test a WebSocket
The oneshot helper sends a request through the router in memory, with no network socket anywhere. A WebSocket upgrade needs a real TCP connection, because the handshake is an HTTP request that says "upgrade this connection", and the upgrade only means something if the connection stays open afterwards. In memory, there is no connection to keep open, so the upgrade has nowhere to go.
That is the whole reason this page starts a real server. The test is no longer calling a function. It is running a program, on a port, and talking to it over the loopback network, the same way a browser would. The cost is a real socket and a background task. The benefit is a test that exercises the handshake, the framing, and the echo loop exactly as a client would.
Starting the Server, Piece by Piece
The start_server helper does three things, and each one matters:
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
Binding to port 0 asks the operating system to pick a free port. The test never names a port, so two tests can start two servers at the same time without colliding, and a server left running from an earlier run cannot block a later one. The address 127.0.0.1 means the server only listens on the local machine, which is right for a test.
let addr = listener.local_addr().unwrap();
local_addr reads back the port the operating system chose, so the test knows where to connect. The address is a SocketAddr, holding the IP and the port together, and formatting it into the URL gives a string like ws://127.0.0.1:45231.
tokio::spawn(async move {
axum::serve(listener, axum_project::ws_app()).await.unwrap();
});
The server runs in a spawned task, so the test can go on to connect while the server runs in the background. axum::serve takes the listener and the router, and the .await inside the spawned future keeps it running until the process ends. The spawned task ends when the test process exits, so there is nothing to shut down by hand. The listener is already bound before the spawn, so the operating system queues incoming connections even in the brief moment before the serve loop starts accepting them.
The Handshake and the First Message, Piece by Piece
let (mut ws, response) = connect_async(format!("{base}/ws")).await.unwrap();
connect_async takes the URL, performs the handshake, and returns two values: the WebSocket stream, and the HTTP response from the upgrade. The URL starts with ws://, which is the WebSocket form of http://. The stream is the socket the test talks on, and the response is the handshake answer.
assert_eq!(response.status(), 101);
The handshake answers with status 101, Switching Protocols, which is the server saying the connection is now a WebSocket connection and no longer plain HTTP. That assertion is the test that the upgrade happened. A plain HTTP handler on the same path would answer 200, and a missing route would answer 404, so the 101 pins down that the endpoint really upgraded.
ws.send(Message::Text("hello".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("hello".into()));
send writes a text message to the socket. The Message::Text value is built from the string with .into(), which converts it into Utf8Bytes. next waits for the next message from the server and returns it wrapped in two layers: an Option, because the stream can end, and a Result, because receiving can fail. The test unwraps both and compares the message with the one it sent. Equality here means the echo returned the exact payload, unchanged.
ws.close(None).await.unwrap();
close sends a close frame and ends the conversation politely. The None means no close code or reason is attached. Closing matters because a test that leaves sockets open leaves the server task holding them, and a suite full of such tests accumulates open connections. Close when the conversation is done.
The Concept Behind It
A WebSocket test has two actors, and the test plays one of them. The server is the system under test, and the client is the test's instrument, a real client that speaks the real protocol. That is what makes the test strong: it does not call the handler function directly, and it does not fake the handshake. It performs the handshake over a real socket, sends real frames, and reads real frames back. A bug in the upgrade, in the framing, or in the echo loop shows up here, and it shows up the same way it would for a browser.
The mental model is a telephone call. The handshake is dialling and the other end picking up. The 101 is the voice on the other end saying hello. The messages are the conversation, and the close frame is hanging up. A test that only checks the dialling has not checked the conversation, and a test that only checks one message has not checked that the line stays open for a second one. The test below sends two messages for exactly that reason.
A Richer Complete Example
The echo test above sends one message. A stronger version sends two, checks a binary message, and checks that the socket is really closed at the end:
#[tokio::test]
async fn websocket_echo_round_trip_over_a_real_socket() {
let base = start_server().await;
let (mut ws, response) = connect_async(format!("{base}/ws")).await.unwrap();
assert_eq!(response.status(), 101);
ws.send(Message::Text("hello".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("hello".into()));
ws.send(Message::Text("second message".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("second message".into()));
ws.close(None).await.unwrap();
}
#[tokio::test]
async fn websocket_echoes_binary_too() {
let base = start_server().await;
let (mut ws, _) = connect_async(format!("{base}/ws")).await.unwrap();
ws.send(Message::Binary(vec![0u8, 1, 2, 3, 255].into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Binary(vec![0u8, 1, 2, 3, 255].into()));
ws.close(None).await.unwrap();
}
#[tokio::test]
async fn sending_after_close_fails() {
let base = start_server().await;
let (mut ws, _) = connect_async(format!("{base}/ws")).await.unwrap();
ws.close(None).await.unwrap();
let result = ws.send(Message::Text("after close".into())).await;
assert!(result.is_err());
}
The second message proves the connection stays open after the first echo, which is the property that makes a WebSocket a conversation rather than a single exchange. The binary test proves the echo loop handles binary frames the same way it handles text, including bytes that are not valid UTF-8, like 255. The close test proves the socket is really done: sending after closing fails, instead of silently dropping the message.
One subtlety: after the client closes, reading the next message from the stream does not give a clean None or a close frame in this setup, because the server ends its loop on the close frame without sending one back, and the client sees the connection reset. The test above avoids asserting on the read after close, and asserts on the send instead, which is the behaviour that is stable: a send on a closed socket fails.
Do Not Assert on the Read After Close:
After the client sends a close frame, the next read from the stream reports an error about the connection resetting without a closing handshake, because the echo handler returns on the close frame instead of answering it. That error is normal for this server shape, and it is not a failure. Assert on the send after close, which reliably fails, and leave the read after close alone.
An Authenticated WebSocket
A protected WebSocket checks the token before the upgrade, and the extractor runs before the handler body, exactly as it does for plain HTTP routes. The handler below takes an AuthUser alongside the upgrade, so a request without a valid token is rejected with 401 before any socket exists:
use crate::{auth::AuthUser, state::TestState};
async fn ws_auth_echo(ws: WebSocketUpgrade, user: AuthUser) -> Response {
let user_id = user.user_id;
ws.on_upgrade(move |socket| async move {
let _ = user_id;
echo_loop(socket).await;
})
}
pub fn ws_app_with_auth(state: TestState) -> Router {
Router::new()
.route("/ws", get(ws_echo))
.route("/ws-auth", get(ws_auth_echo))
.with_state(state)
}
The test app carries the secret in state, the same way the authenticated-request page does, so the tests run without a database. The client sends the token as a header, and building a request with a header needs the IntoClientRequest trait, which turns a Request into something connect_async accepts:
use axum_project::token_for;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
#[tokio::test]
async fn websocket_with_a_valid_token_opens_the_protected_socket() {
let base = start_server().await;
let token = token_for(1, "user");
let mut request = format!("{base}/ws-auth").into_client_request().unwrap();
request.headers_mut().insert(
"authorization",
format!("Bearer {token}").parse().unwrap(),
);
let (mut ws, response) = connect_async(request).await.unwrap();
assert_eq!(response.status(), 101);
ws.send(Message::Text("auth hello".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("auth hello".into()));
ws.close(None).await.unwrap();
}
into_client_request builds the handshake request from the URL, filling in the WebSocket headers, the upgrade headers, and a fresh key, so the test only adds the one header it cares about. Passing a plain URL string to connect_async is the shorthand for the same thing with no extra headers. The test then asserts the handshake succeeded and the echo works, which proves the token was accepted and the socket is usable.
The negative case is the handshake failing. A connection without a token never becomes a WebSocket, so connect_async returns an error, and the error carries the HTTP response the server sent:
#[tokio::test]
async fn websocket_without_a_token_fails_the_handshake_with_401() {
let base = start_server().await;
let error = connect_async(format!("{base}/ws-auth")).await.unwrap_err();
match error {
tokio_tungstenite::tungstenite::Error::Http(response) => {
assert_eq!(response.status(), 401);
}
other => panic!("expected an HTTP handshake error, got {other:?}"),
}
}
unwrap_err flips the result: it panics if the connection succeeded, and returns the error if it failed. The match then checks the error is the HTTP kind, which carries the response, and asserts the response status is 401. Any other error kind, like a connection failure, panics with a message naming what actually happened, so the failure points at the real cause instead of a bare assertion.
Client sends upgrade request with Authorization header
|
v
Extractor verifies the token (401 if missing or bad)
|
v
Server answers 101 Switching Protocols
|
v
Client and server exchange messages on the open socket
|
v
Client sends a close frame, conversation ends
Common Beginner Mistakes
Testing a WebSocket with oneshot
// Wrong - oneshot has no socket, so the upgrade has nowhere to go
let response = ws_app()
.oneshot(Request::builder().uri("/ws").body(Body::empty()).unwrap())
.await
.unwrap();
A oneshot request to a WebSocket route cannot complete the handshake, because there is no TCP connection to upgrade. The test needs a real server on a real port, as this page shows. Any WebSocket test that starts with oneshot is testing the wrong thing, and the failure it produces will look like a routing problem when the real problem is the missing socket.
Hardcoding a port
// Wrong - the port may already be taken, and parallel tests collide on it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
Port 3000 may be in use by a server left running from an earlier run, or by another test that started at the same moment. The bind then fails, and the test fails for a reason that has nothing to do with the code. Bind to port 0 and read the chosen port back, as start_server does. The operating system picks a free port every time.
Comparing a text message with a plain string
// Wrong - Message::Text holds Utf8Bytes, not &str, so this does not compile
assert_eq!(reply, "hello");
The reply is a Message, and its text variant holds Utf8Bytes. Comparing it with a string literal is a type error. Compare it with Message::Text("hello".into()), as the tests above do, or match on the message and compare the payload with as_str(). The compiler error here names the mismatch directly, and the fix is to build the expected value in the same type as the received one.
Forgetting the ws feature
// Wrong - without the ws feature, WebSocketUpgrade does not exist
axum = "0.8"
The WebSocketUpgrade extractor, the WebSocket type, and the Message enum all live behind the ws feature of axum. Without it, the imports fail and the compiler reports the names as unresolved. The fix is one word in Cargo.toml: axum = { version = "0.8", features = ["ws"] }.
A Test That Never Connects Hangs Forever:
connect_async waits for the server to answer the handshake. If the server never started, because the spawn failed or the router has no route at the path, the connect waits until the test times out, and the failure is a hang rather than an assertion. When a WebSocket test hangs, check first that the server task is running and that the path in the URL matches a route in the app. A wrong path is the most common cause.
Final Complete Example
The whole test file, with the server helper and all five tests, against the app from this page. The authenticated tests use the token helper and the test state from the authenticated-request page, with the secret carried in state:
use axum_project::{test_state, token_for, ws_app_with_auth};
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::{
connect_async,
tungstenite::{Message, client::IntoClientRequest},
};
async fn start_server() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, ws_app_with_auth(test_state().await)).await.unwrap();
});
format!("ws://{addr}")
}
#[tokio::test]
async fn websocket_echo_round_trip_over_a_real_socket() {
let base = start_server().await;
let (mut ws, response) = connect_async(format!("{base}/ws")).await.unwrap();
assert_eq!(response.status(), 101);
ws.send(Message::Text("hello".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("hello".into()));
ws.send(Message::Text("second message".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("second message".into()));
ws.close(None).await.unwrap();
}
#[tokio::test]
async fn websocket_echoes_binary_too() {
let base = start_server().await;
let (mut ws, _) = connect_async(format!("{base}/ws")).await.unwrap();
ws.send(Message::Binary(vec![0u8, 1, 2, 3, 255].into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Binary(vec![0u8, 1, 2, 3, 255].into()));
ws.close(None).await.unwrap();
}
#[tokio::test]
async fn websocket_with_a_valid_token_opens_the_protected_socket() {
let base = start_server().await;
let token = token_for(1, "user");
let mut request = format!("{base}/ws-auth").into_client_request().unwrap();
request.headers_mut().insert(
"authorization",
format!("Bearer {token}").parse().unwrap(),
);
let (mut ws, response) = connect_async(request).await.unwrap();
assert_eq!(response.status(), 101);
ws.send(Message::Text("auth hello".into())).await.unwrap();
let reply = ws.next().await.unwrap().unwrap();
assert_eq!(reply, Message::Text("auth hello".into()));
ws.close(None).await.unwrap();
}
#[tokio::test]
async fn websocket_without_a_token_fails_the_handshake_with_401() {
let base = start_server().await;
let error = connect_async(format!("{base}/ws-auth")).await.unwrap_err();
match error {
tokio_tungstenite::tungstenite::Error::Http(response) => {
assert_eq!(response.status(), 401);
}
other => panic!("expected an HTTP handshake error, got {other:?}"),
}
}
#[tokio::test]
async fn sending_after_close_fails() {
let base = start_server().await;
let (mut ws, _) = connect_async(format!("{base}/ws")).await.unwrap();
ws.close(None).await.unwrap();
let result = ws.send(Message::Text("after close".into())).await;
assert!(result.is_err());
}
Dependencies for the Final Example:
The echo tests need only the Cargo.toml from the smallest version. The two authenticated tests also need the auth dependencies from the previous page: serde_json, jsonwebtoken version 12 with the rust_crypto feature, and argon2 version 0.6, plus the auth and state modules that define token_for and test_state. The unauthenticated app builder ws_app and the authenticated builder ws_app_with_auth live side by side, and the final test file uses the authenticated one, which serves both routes.
Run the tests with:
cargo test --test ws_test
All five tests pass. The echo works for text and binary, the handshake answers 101, the authenticated socket opens with a valid token and refuses without one, and a send after close fails.
Summary
A WebSocket test is a conversation between two real endpoints, and the test has to build both sides: a server on a random port, and a client that dials it. The 101 status proves the upgrade, the echoed messages prove the loop, and the 401 on the handshake proves the extractor runs before any socket exists. The shape is different from every earlier test in this chapter, because the thing under test is a connection that stays open, not a call that returns.
The decision to carry forward is to test WebSockets over the network, never in memory, and to let the operating system pick the port, so the tests stay fast, parallel, and free of collisions. The next page does the same kind of work for the other streaming transport, where the server sends a stream of events and the test reads them one frame at a time.