I am following the documentation to unit test a ktor API. In particular configuring the HttpClient for ContentNegociation with conversion of a class to JSON (https://ktor.io/docs/testing.html#configure-client)
Note the application starts and the POST endpoint works.
Here is the test code:
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)
}
}
The problem is that the compilation fails saying:
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
If needed, my partial 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")
}
I believe this is exactly as in the example, I don't know why it is failing to compile.
So it turned out I needed a different ContentNegociation plugin, from the client package. In the build.gradle.kts:
dependencies {
// ...
testImplementation("io.ktor:ktor-client-content-negotiation:2.1.1")
}
and in the test, use the correct import:
import io.ktor.client.plugins.contentnegotiation.*
// ...
@Test
fun testPostDeviceInformation() = testApplication {
val httpClient = createClient {
install(ContentNegotiation) {
json()
}
}
// ...
}
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With