kotlintestingktor

Ktor integration test with custom hostname AND port


Using ktor-testing I need to create a test which uses a custom hostname and port at the same time. See my previous question with custom hostname on port 80 which works, but not on port 8080.

class MyApplicationTest {

    @Test
    fun testCustomHostnameAndPort() = testApplication {

        environment {
            connector {
                port = 8080
                host = "example.com"
            }
        }

        application {
            routing {
                host("example.com", port = 8080) {
                    get("/my-path") {
                        call.respond(HttpStatusCode.Accepted)
                    }
                }
            }
        }

        val response = client.get("http://example.com:8080/my-path") {
            header(HttpHeaders.Host, "example.com")
        }

        assertEquals(HttpStatusCode.Accepted, response.status)
    }
}

This test gives 404 Not Found instead of 202 Accepted.

But if I change from host("example.com", port = 8080) to host("example.com", port = 80) while keeping 8080 in connector and url it works strangely enough.

And if I change from host("example.com", port = 8080) to host("example.com", port = 0) (which means all ports) it also works. But I need to limit it to port 8080 as I have other connectors with different ports, so this is no solution.

And I can also make it work by switching from example.com to localhost (and removing host header) on 8080, but I need a custom hostname.


Solution

  • As per my previous answer, you can adjust the Host header accordingly to solve your problem:

    val response = client.get("http://example.com:8080/my-path") {
        header(HttpHeaders.Host, "example.com:8080") // Here
    }