https://kotlinlang.org logo
Title
k

Ky

06/20/2022, 6:59 PM
Does Ktor’s
HttpClient
kick off it’s own coroutine to make requests? And do we have any control over that coroutineContext? I’m having trouble getting ktors HttpClient to behave nicely in regards to synchronization. Unless I wrap the
.get()
in
withContext(runTest.coroutineContext)
my tests do not wait for ktor request to return and the test will complete prematurely
a

Aleksei Tirman [JB]

06/21/2022, 9:07 AM
The
HttpClient
implements
CoroutineScope
and has public
coroutineContext
property.
HttpClient().coroutineContext
Could you please share the code for your test?
k

Ky

06/29/2022, 3:25 PM
Yes it has coroutine context but it can not be changed.
runTest {
            client.engine.coroutineContext = this.coroutineContext
            viewModel.getMain()
        }
Essentially without wrapping the HttpClient call in
withContext(someContext)
and setting
someContext
as TestScope.coroutineContext. The test will complete before HttpClient call returns. I’m having trouble acheiving synchronous mechanism without wrapping in
withContext
@Aleksei Tirman [JB]
a

Aleksei Tirman [JB]

06/30/2022, 9:37 AM
Could you please share the definition of the
runTest
function? In what environment the
runTest
is executed?
p

Piasy

07/24/2022, 4:16 AM
@Ky If you use MockEngine, you could inject your test dispatcher.
val engine = MockEngine.config {
    dispatcher = StandardTestDispatcher(testScheduler)

    addHandler {
        respondOk(resp)
    }
}

val http = HttpClient(engine)
// inject the http client into your code