我想找到一个用于 android UI 测试(聊天)的普通 websocket 模拟服务器解决方案。我找到了这个例子
但是我在这里看不到如何重现这种情况:
MockWebServer(它也来自 OkHttp 生态系统)? MockWebServer 将允许您编写响应脚本、延迟响应以及对传入请求进行断言。
这是一个如何做到这一点的想法:
testImplementation 'com.squareup.okhttp3:mockwebserver:4.x.x'
MockWebServer mockWebServer = new MockWebServer();
mockWebServer.start();
WebSocketEchoServer webSocketEchoServer = new WebSocketEchoServer();
mockWebServer.enqueue(new MockResponse().withWebSocketUpgrade(webSocketEchoServer));
// ... point your app WebSocket client to: mockWebServer.url("/yourEndpoint")
private static class WebSocketEchoServer implements WebSocketListener {
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Welcome!"); // Initial message when the connection is opened.
}
@Override
public void onMessage(WebSocket webSocket, String text) {
if ("RegisterDevice".equals(text)) {
webSocket.send("Device Registered Successfully!"); // Mock reply.
} else {
webSocket.send(text); // Echo back the same message for other inputs.
}
}
// Handle other WebSocket events (onClosing, onClosed, onFailure) as needed.
}
mockWebServer.takeRequest()
断言收到的 WebSocket 消息,然后使用
mockWebServer.shutdown()
进行清理。
希望有帮助。