You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ktor Testing自定义主机名编写集成测试遇404问题

Ktor测试自定义主机名返回404的解决方法

你的测试返回404是因为路由通过host("example.com")做了匹配,但测试客户端的请求没有正确传递Host头,导致路由无法匹配。

在Ktor的testApplication环境中,内嵌服务器不需要实际的域名解析,只需要在请求中添加正确的Host头,就能匹配指定host的路由规则。

修改后的测试代码如下:

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") {
            // 添加Host头匹配路由规则
            headers.append(HttpHeaders.Host, "example.com")
        }

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

另外也可以简化环境配置,因为测试环境的connector主机配置不影响路由匹配,核心是请求的Host头要和路由的host条件一致。

内容的提问来源于stack exchange,提问作者actonchart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:04:56