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

如何测试Ktor中带子域名的Host路由逻辑?

如何测试Ktor中带子域名约束的路由?

我在Ktor中配置了监听api子域名下的/v1路径,部署后请求http://api.my.test:8080/v1可以正常响应,但用Kotest编写测试时遇到错误。

我的配置

Application启动配置

fun Application.configure() {
    // ...
    routing {
        myApi()
    }
}

路由定义

fun Route.myApi() {
    host("api.${environment?.config?.host}") {
        get("v1") { call.respondText("My api is here") }
    }
}

配置文件(application.conf)

ktor {
  deployment {
    host = "my.test"
    port = 8080
  }

  application {
    modules = [my.configuration.KtorKt.configure]
  }
}

测试代码

class ServerTest : FunSpec({
    test("my test") {
        testApplication {
            val response = client.get("http://api.my.test:8080/v1")
        }
    }
})

遇到的错误

Can not resolve request to http://api.my.test:8080. Main app runs at localhost:80, localhost:443 and external services are


解决方法

问题根源在于testApplication默认将测试服务器运行在localhost,且不会解析自定义域名。直接请求完整的子域名地址会被当成外部服务请求,导致无法解析。可以通过以下两种方式解决:

方法1:添加Host请求头

无需指定完整域名,直接请求路径,同时在请求中添加Host头指定目标子域名即可:

class ServerTest : FunSpec({
    test("my test") {
        testApplication {
            val response = client.get("/v1") {
                headers.append(HttpHeaders.Host, "api.my.test")
            }
            // 验证响应状态和内容
            response.status shouldBe HttpStatusCode.OK
            response.bodyAsText() shouldBe "My api is here"
        }
    }
})

方法2:覆盖测试环境的配置

如果需要让测试环境的host配置与生产环境保持一致,可以在testApplication中覆盖配置,同时配合Host头请求:

class ServerTest : FunSpec({
    test("my test") {
        testApplication {
            environment {
                config = HoconApplicationConfig(ConfigFactory.parseString("""
                    ktor {
                        deployment {
                            host = "my.test"
                        }
                    }
                """))
            }
            val response = client.get("/v1") {
                headers.append(HttpHeaders.Host, "api.my.test")
            }
            // 验证逻辑
        }
    }
})

注意:testApplication提供的client已经和测试服务器绑定,无需手动指定完整的服务器地址,直接写路径即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:23:19