MockWebSocketTransport class

A fake WebSocket connection for tests: every connection the client opens is kept in memory, and the test plays the server on it.

It replaces the real WebSocketTransport under a WebSocket client (for example one of the WebSocket starter), so a test can read what the client sent, push messages to it, close or drop the connection, and make the next connection attempt fail, all without a server. Each connect succeeds at once and gives a MockWebSocket; wait for it with nextConnection.

// A chat client under test talks to the mock instead of a server.
final sockets = MockWebSocketTransport();
runner = runner.withBean<WebSocketTransport>(() => sockets);

final server = await sockets.nextConnection;
server.pushJson({'from': 'ann', 'text': 'hi'}); // the client receives
expect(server.sentJson, [{'from': 'me', 'text': 'hello'}]);

sockets.failNextConnect(); // the first reconnection attempt fails
await server.drop(); // the connection is lost: the client reconnects

Spring (Java): no equivalent; tests start a server or mock WebSocketSession.

Implemented types

Constructors

MockWebSocketTransport()
A transport that accepts every connection, until failNextConnect says otherwise.

Properties

connections → List<MockWebSocket>
Every connection opened so far, in order, closed ones included.
no setter
hashCode → int
The hash code for this object.
no setterinherited
lastConnection → MockWebSocket
The connection opened last; throws a StateError when none was opened.
no setter
nextConnection → Future<MockWebSocket>
The next connection this getter has not returned yet: the first call gives the first connection, the second call the second, and so on. When the client has not opened it yet, the future completes when it does. This is how a test waits for a (re)connection.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

connect(Uri url, {HttpHeaders? headers, List<String> protocols = const [], Duration? timeout}) → Future<WebSocketSession>
Opens a connection to url (ws: or wss:) and completes once the handshake has succeeded.
override
failNextConnect([Object? error]) → void
Makes the next connect throw error (by default a WebSocketException "connection refused"), to test how the client handles a refused connection. Each call fails one more attempt.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited