I've got an API client class which creates an `Htt...
# ktor
b
I've got an API client class which creates an
HttpClient
and I want to add a hook so I can pass a
MockEngine
in for unit testing, but running into a few issues: My first thought was to have the entire client be a ctor param and default it to what I want, i.e.:
Copy code
class MyClass(
    private val client: HttpClient = HttpClient(Apache) {
        install(JsonFeature) { ... }
    }
) {
but then if I pass in a mock client,
MyClass
won't install the JsonFeature, so next I thought about passing in the engine:
Copy code
class MyClass(
    private val clientEngine: HttpClientEngine = Apache
) {
but this doesn't work because
Apache
isn't an
HttpClientEngine
, it's an
HttpClientEngineFactory
. And I don't want to change the ctor to take in a
HttpClientEngineFactory
because it has a generic type and I don't want to add a generic to the class just to support this. I'm assuming there must be something simple here I'm missing?
Hmm, well I realized if I want to be able to take in a
MockEngine
, then I won't be able to assume it's an ApacheConfig anyway, so I ended up just taking in
HttpClientEngineFactory<*>
.
I guess if I need some Apache-specific setting in the future I'll have to figure something else out.
🤦 just realized that the stubs for requests are in the
MockEngine
config which needs to be applied, so this won't quite work either.
I ended up taking an
HttpClient
in a private constructor of my wrapper and added a generic helper function which takes in
engineFactory: HttpClientEngineFactory<T>
and
block: HttpClientConfig<T>.() -> Unit = {}
rubber duck 1
For anyone who might find this, I did finally stumble onto the better way: take in an
HttpClient
in the ctor, and then call
.config {...}
on it to add more config (which returns a new
HttpClient
with a combination of any original config and the newly-added config)