Hey all. I’m looking for ways to mock Ktor’s HttpC...
# mockk
d
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
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
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
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
Okay, great. Thanks for your help, Russell!
158 Views