Ktor: Ktor HttpClient Mock Fails with JsonFeature

Created on 25 Feb 2020  路  4Comments  路  Source: ktorio/ktor

Ktor Version and Engine Used (client or server and name)
Client 1.3.1

Describe the bug
When trying to use HttpClient mockengine I get this excetion:

io.ktor.client.call.NoTransformationFoundException: No transformation found: class kotlinx.coroutines.io.ByteBufferChannel -> class kotlinx.serialization.json.JsonObject
with response from http://localhost/dsf:
status: 200 OK
response headers: 
Content-Type: application/json


    at io.ktor.client.call.HttpClientCall.receive(HttpClientCall.kt:79)

To Reproduce
Run this test:

@Test
fun mockFailure() = runBlocking {
    val mock = MockEngine { call ->
        respond("{}",
                HttpStatusCode.OK,
                headersOf("Content-Type", ContentType.Application.Json.toString()))
    }

    val client = HttpClient(mock) {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }

    val resp =  client.get<JsonObject>("dsf")
}

Expected behavior
Should parse the response to JsonObject using Kotlin serialization.

This appears to be similar to #615 but that issues appears to have been fixed.

Client bug

Most helpful comment

@frevib You need to add "content-type" "application/json" to your response headers.

All 4 comments

I found the issue. KotlinxSerializer() doesn't take Json object. Once I added a passed in my Json object it worked.

@jeffgnpc Could you elaborate on what you exactly did to fix this? I'm stuck here as well.

@frevib You need to add "content-type" "application/json" to your response headers.

val client = HttpClient(mock) {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }

Needed to be:

val client = HttpClient(mock) {
        install(JsonFeature) {
            serializer = KotlinxSerializer(Json {
                   ignoreUnknownKeys = true
                   encodeDefaults = true 
            })
        }
    }
Was this page helpful?
0 / 5 - 0 ratings