https://kotlinlang.org logo
#mockk
Title
# mockk
d

Dave Leeds

03/27/2020, 8:29 PM
Hey all. I’m looking for ways to mock Ktor’s HttpClient with mockk for unit tests. I’ve tried the usual approach:
Copy code
coEvery { httpClient.hint(MyPayload::class).get<MyPayload>(any<String>()) }.returns(examplePayload)
But this fails with a class cast exception:
Copy code
MyPayload cannot be cast to io.ktor.client.call.HttpClientCall
I suspect the reason for this is that the entire call stack between the test and
HttpStatement.executeUnsafe()
is made up of
inline
functions. I tried to mock
httpClient.execute()
since that’s ultimately what gets invoked, but that’s marked as
@InternalAPI
. Any ideas?
r

russhwolf

03/27/2020, 8:47 PM
ktor has some built-in mocking helpers that might be easier to work with. You can pass the client a
MockEngine
where you can control what responses it serves.
d

Dave Leeds

03/27/2020, 9:19 PM
Thanks Russell. I’ll take a closer look at that one. Do you know if that would require my mocked responses to be expressed as, say JSON strings, rather than as the model classes that they deserialize into?
r

russhwolf

03/27/2020, 9:30 PM
Yes it does, at least how I've used it. So, if that complicates things too much then it may not be what you want. It has the advantage though of verifying that your model classes serialize the json in the way you expect.
d

Dave Leeds

03/27/2020, 9:36 PM
Okay, great. Thanks for your help, Russell!
126 Views