I am an Android developer. I'm using Retrofit and ...
# ktor
y
I am an Android developer. I'm using Retrofit and had previously created and used interceptors for testing purposes. These interceptors would intercept cases difficult to reproduce in the actual production environment and force mock responses. I'm gradually migrating the app from Retrofit to Ktor. Therefore, I need an interceptor for Ktor that intercepts responses and replaces them with desired values. I've been researching this and asking GPT, Grok, and Gemini, but it's not working as intended. I understand I need to create a custom plugin. However, I couldn't achieve the desired result using onRequest or onResponse blocks. While I can intercept requests and trigger side effects, I can't actually return a response. I'm looking into transformResponseBody, but it also isn't working as intended. When I run very simple code like this, it throws an IllegalStateException.
Copy code
val ktorInterceptor = createClientPlugin("InterceptorPlugin") {
  transformResponseBody { response, content, requestedType ->
    content
  }
}

...

HttpClient(Android) {
  install(Logging) {
    logger = Logger.ANDROID
  }

  install(ktorInterceptor)
}

suspend fun getUser(): RespUser {
    return client.get(url).body()
}

-> java.lang.IllegalStateException: transformResponseBody returned io.ktor.utils.io.SourceByteReadChannel@7e05379 but expected value of type TypeInfo(RespUser (Kotlin reflection is not available))
How can I resolve this? I also asked on the stackoverflow too
s
Hey @Yoonho Aaron Kim, Ktor has support for mocking the test client out-of-the-box. Have you considered using that instead of interceptors for replacing the responses? https://ktor.io/docs/client-testing.html#test-client
y
Thank you @simon.vergauwen I already check it. However, the functionality I require fundamentally involves normal HTTP communication with the server, along with the ability to dynamically mock specific URL paths. To achieve this, I need to dynamically receive input from the user for the path to mock, as well as dynamically input the JSON response body and response code for the mock. It seems the MockEngine you mentioned does not meet these requirements.
a
I've answered your question on StackOverflow.
kodee loving 2
j
Ktor client abstracts over OkHttp the same way Retrofit does. You shouldn't have to change a thing.
☝️ 2
y
Thank you @Aleksei Tirman [JB] I will try!