使用相依注入進行測試
必要的相依性:io.ktor:ktor-server-di
程式碼範例: server-di
相依注入 (DI) 外掛程式 提供了解化測試的工具。
您可以在載入應用程式模組之前覆寫相依性:
kotlin
fun test() = testApplication {
application {
dependencies.provide<MyService> {
MockService()
}
loadServices()
}
}在上述範例中,loadServices() 是用於引導應用程式模組的函式 — 例如,註冊路由和服務的函式,等同於 application.yaml 中 modules 下方列出的內容。
在測試中載入配置
在測試中使用 configure() 即可輕鬆載入配置檔案:
kotlin
fun test() = testApplication {
// 從預設配置檔案路徑載入屬性
configure()
// 載入多個檔案並進行覆寫
configure("root-config.yaml", "test-overrides.yaml")
}測試引擎會忽略衝突的宣告,讓您可以自由地進行覆寫。
