无法在 testApplication 中安装 ContentNegotiation

Sir*_*ode 6 kotlin ktor

我正在按照文档对 ktor API 进行单元测试。特别是通过将类转换为 JSON 来配置 ContentNegociation 的 HttpClient ( https://ktor.io/docs/testing.html#configure-client )

请注意,应用程序启动并且 POST 端点工作。

这是测试代码:

class DeviceInformationRouteTest {

    @Test
    fun testPostDeviceInformation() = testApplication {
        val client = createClient {
            install(ContentNegotiation) { // Error on the `install` call
                json()
            }
        }
        val deviceInformation = DeviceInformation("test")

        val response = client.post("/deviceInformation") {
            setBody(deviceInformation)
        }
        assertEquals("""{"value": "test"}""",response.bodyAsText())
        assertEquals(HttpStatusCode.OK, response.status)
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是编译失败并显示:

DeviceInformationRouteTest.kt: (19, 13): 'fun <P : Pipeline<*, ApplicationCall>, B : Any, F : Any> install(plugin: Plugin<ApplicationCallPipeline, ContentNegotiationConfig, PluginInstance>, configure: ContentNegotiationConfig.() -> Unit = ...): Unit' can't be called in this context by implicit receiver. Use the explicit one if necessary
Run Code Online (Sandbox Code Playgroud)

如果需要,我的部分 build.gradle:


plugins {
    application
    kotlin("jvm") version "1.7.10"
    id("io.ktor.plugin") version "2.1.1"
    id("org.jetbrains.kotlin.plugin.serialization") version "1.7.10"
}

dependencies {
    implementation("io.ktor:ktor-server-content-negotiation-jvm:2.1.1")
    implementation("io.ktor:ktor-server-core-jvm:2.1.1")
    implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:2.1.1")
    implementation("io.ktor:ktor-server-netty-jvm:2.1.1")
    testImplementation("io.ktor:ktor-server-tests-jvm:2.1.1")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit:1.7.10")
}
Run Code Online (Sandbox Code Playgroud)

我相信这与示例中的完全一样,我不知道为什么它无法编译。

Sir*_*ode 10

结果我需要一个ContentNegociation来自客户端包的不同插件。在里面build.gradle.kts

dependencies {
    // ...
    testImplementation("io.ktor:ktor-client-content-negotiation:2.1.1")
}
Run Code Online (Sandbox Code Playgroud)

并在测试中使用正确的导入:

import io.ktor.client.plugins.contentnegotiation.*

// ...
    @Test
    fun testPostDeviceInformation() = testApplication {
        val httpClient = createClient {
            install(ContentNegotiation) {
                json()
            }
        }
    // ...
    }
// ...
Run Code Online (Sandbox Code Playgroud)