Using ktor-testing I need to create a test which uses a custom hostname. (The reason I need this is that we use subdomains to select the upstream service, but that's not really important).
Anyway, I came up with this:
class MyApplicationTest {
@Test
fun testCustomHost() = testApplication {
environment {
connector {
port = 80
host = "example.com"
}
}
application {
routing {
host("example.com") {
get("/my-path") {
call.respond(HttpStatusCode.Accepted)
}
}
}
}
val response = client.get("/my-path") {
url {
this.port = 80
this.host = "example.com"
this.protocol = URLProtocol.HTTP
}
}
assertEquals(HttpStatusCode.Accepted, response.status)
}
}
This test gives 404 Not Found instead of 202 Accepted. But if I change from "example.com" to "localhost" it works.
To solve the problem, send the Host
header with the value example.com
:
val response = client.get("http://example.com/my-path") {
header(HttpHeaders.Host, "example.com")
}