junitokhttpmockwebserver

Using Okhttp.MockWebServer for testing websocket


I am using okhttp.MockWebServer to test rest api calls. Is there a way to use it for mocking a websocket call as well?

Essentially, I have a ws client (Client extends WebSocketListener) which calls an external websocket server and gets back responses asynchronously. I want to mock this server so it can be used for junit test.

Any ideas?

Thanks


Solution

  • Look at the tests in https://github.com/square/okhttp/blob/f8fd4d08decf697013008b05ad7d2be10a648358/okhttp/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java

    
      @Test public void serverMessage() {
        webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));
        WebSocket webSocket = newWebSocket();
    
        clientListener.assertOpen();
        WebSocket server = serverListener.assertOpen();
    
        server.send("Hello, WebSockets!");
        clientListener.assertTextMessage("Hello, WebSockets!");
    
        closeWebSockets(webSocket, server);
      }