Hi Team! I'm still new to ktor/kotlin, and have been playing around with the framework for websocket...
j
Hi Team! I'm still new to ktor/kotlin, and have been playing around with the framework for websocket development. My current project is a websocket proxy (we accept a ws connection, and create a connection to another backend ws server, and route messages between them). The code works fine, but I'm having issues with setting up tests for this, specifically with trying to mock out the backend ws server with
externalServices
. This is the mock I have right now in my `testApplication`:
Copy code
externalServices {
    hosts("<ws://test.com>") {
        install(io.ktor.server.websocket.WebSockets) {}
        routing {
            webSocket("/") {
                this.send("hello")
            }
        }
    }
}
My test will hang when it tries to connect to
<ws://test.com>
and eventually return a
io.ktor.client.network.sockets.ConnectTimeoutException: Connect timeout has expired [url=<ws://test.com>, connect_timeout=unknown ms]
error. Can
externalServices
mock out ws servers? If not, are there any suggestions on how to mock a ws server for testing? Thank you!
Running the debugger seems to indicate none of the mocked external services code gets hit, so my assumption is that ws endpoints just can't be mocked with external services? Can anyone confirm?
a
The following test passes:
Copy code
@Test
fun test() = testApplication {
    externalServices {
        hosts("<ws://test.com>") {
            this@hosts.install(WebSockets) {}
            this@hosts.routing {
                webSocket("/") {
                    this.send(Frame.Text("hello"))
                }
            }
        }
    }

    val client = createClient {
        install(io.ktor.client.plugins.websocket.WebSockets)
    }

    client.webSocket("<ws://test.com>") {
        val frame = incoming.receive()
        assertIs<Frame.Text>(frame)
        assertEquals("hello", frame.readText())
    }
}