Hello guys! I was wondering here if any of you ha...
# mockk
h
Hello guys! I was wondering here if any of you have already mocked Ktor HttpResponse. I've tried as the following. Do you have any suggestion? https://kotlinlang.slack.com/archives/C0A974TJ9/p1610688463022200
c
thats really a bad idea, use HttpClient(MockEngine) instead
h
Thanks so much for getting back to me @christophsturm, Yes, I was previously using HttpClient(MockEngine), however, with Ktor version 1.5.0, it looks like instead of mocking it the exception is being thrown. This is what I had previously.
Copy code
private fun mockHttpErrorResponse(httpStatusCode: HttpStatusCode): HttpResponse {
        val client = HttpClient(MockEngine) {
            engine {
                addHandler {
                    respondError(httpStatusCode)
                }
            }
        }
        return runBlocking { client.get() }
    }
For instance, the test I had was something like this…
Copy code
@Test
    fun bbcPipelinesBuildInfoThrowClientException(): Unit = withTestApplication(Application::module) {
        val compliantToken = TokenatorTokenModelEntityBuilder.BUILD_COMPLIANT_TOKEN
        declareMock<BbcPipelineBuildInfoServiceImpl> {
            coEvery {
                getBitbucketPipelineBuildInfo(any(), any(), any(), any(), any(), any())
            } throws ClientRequestException(mockHttpErrorResponse(HttpStatusCode.Unauthorized))
        }
        declareMock<TokenatorServiceImpl> { coEvery { generateToken(any(), any()) } returns compliantToken }
        with(handleRequest(<http://HttpMethod.Post|HttpMethod.Post>, "token/build") {
            SlauthHeadersBuilder.BUILD_PRINCIPAL_HEADERS.forEach { (key, value) -> addHeader(key, value) }
        }) {
            assertThat(HttpStatusCode.InternalServerError).isEqualTo(response.status())
        }
    }
This was working fine with ktor 1.4.0, 1.4.2, 1.4.3. But it doesn’t work with 1.5.0. To be more specific, debugging the test, it doesn’t even reach the following line,
declareMock<TokenatorServiceImpl> { coEvery { generateToken(any(), any()) } returns compliantToken }
Which, is the exactly line after trying to mock the HttpResponse.
c
and what exception do you get?
h
Sorry for sending as a screenshot, but I think it will be easier to show the details.
My understanding is that the
runBlocking {client.get() }
throws the exception, instead of just “create” the response and mock it silently.
c
you are right, thats really strange, but I would try to get help in the ktor channel.
h
Yep. I have tried, but didn't get a reply. I will probably get the link of this thread and throw it there. I will also keep watching for Ktor updates. Thanks so much for your help Christoph
c
yw!