使用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
相关产品推荐
相关产品推荐

