テスト
MockWebSocketTransport はクライアントに対してサーバー役を演じます。テストはクライアントが送ったものを読み、メッセージを送り出し、再接続を確認するために接続を切ります。MockMvc.webSocket(path) は、同じフィルターとハンドシェイクを通して、メモリ上でサーバーのエンドポイントへの接続を開きます。どちらも spring_boot_starter_test に含まれます。
使う理由
本物の WebSocket サーバーを必要とするテストは遅く、操作しにくいものです。ちょうどよいタイミングで接続を切らせるのは簡単ではありません。モックを使えば、クライアントとエンドポイントのコードは本番と同じままで、相手側をテストが制御できます。
クライアント
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';
import 'spring_gen/main.test.spring.dart';
void main() {
final sockets = MockWebSocketTransport();
final app = springBootTest(
springApplication,
overrides: [BeanOverride<WebSocketTransport>(sockets)],
properties: {'chat.url': 'ws://chat.test/ws'},
);
test('chats', () async {
final chat = app.getBean<ChatSocket>();
final messages = <ChatMessage>[];
chat.messages().listen(messages.add); // 接続を開く
final server = await sockets.nextConnection;
server.pushJson({'from': 'ann', 'text': 'hi'}); // サーバー → クライアント
await chat.send(const ChatMessage(from: 'me', text: 'hello'));
expect(server.sentJson, [{'from': 'me', 'text': 'hello'}]);
await server.drop(); // 接続が失われ...
await sockets.nextConnection; // ...クライアントが再接続する
});
}
ApplicationContextRunner では、.withBean<WebSocketTransport>(() => sockets) でモックを登録します。
サーバーのエンドポイント
final app = springBootTest(springApplication);
test('acknowledges a message', () async {
final session = await app.mockMvc.webSocket(
'/ws/rooms/neon',
headers: {'Origin': 'https://chat.example'},
);
final replies = StreamIterator(session.messages);
session.sendMessage('{"from": "ann", "text": "hi"}');
// まず、このセッションを含むルームへのブロードキャスト...
expect(await replies.moveNext(), isTrue);
expect(jsonDecode(replies.current as String), {'from': 'ann', 'text': 'hi'});
// ...次に @OnMessage の返信。
expect(await replies.moveNext(), isTrue);
expect(jsonDecode(replies.current as String), {'room': 'neon', 'received': 'hi'});
await session.close();
});
(オリジンのチェックやインターセプターによって) 拒否されたハンドシェイクは、ステータスを持つ WebSocketException を投げます。
生成されたアプリケーションを使わず、コンテキストを手で組み立てるテストは、サーバーのエンドポイントを持つ場合、スターターの両方のモジュールを指定します。springBootStarterWebsocketAutoConfiguration (クライアント) と springBootStarterWebsocketServerAutoConfiguration (セッションレジストリとハンドシェイクのマッピング) です。前者だけでは、エンドポイントは一つもマッピングされません。
本物のソケットで
空きポートでサーバーを起動し、クライアントのトランスポートで接続します。
final app = springBootTest(springApplication, webEnvironment: WebEnvironment.randomPort);
test('over a socket', () async {
final session = await platformWebSocketTransport()
.connect(Uri.parse('ws://127.0.0.1:${app.localServerPort}/ws/rooms/neon'));
session.sendMessage('{"from": "ann", "text": "hi"}');
await session.close();
});
Spring (Java) との対応
Spring は、本物のサーバー (@SpringBootTest(webEnvironment = RANDOM_PORT)) と StandardWebSocketClient で WebSocket のエンドポイントをテストします。MockMvc.webSocket と MockWebSocketTransport はこのプロジェクト独自のものです。