https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Adam Grzybkowski

03/27/2020, 12:25 PM
Hi! I have a problem with testing the Flow using FlowAssert from SqlDelight library. It might be related to FlowAssert, but tbh I feel like I know nothing right now :D I created a repo with the problem here, you can find there two branches
master
and
sqldelight
On master branch I've tried to reproduce the original problem I've encountered when testing SqlDelight but without the SqlDelight code. The problem Tests are stuck when
TestCoroutineDipsatcher
is injected and used in
flowOn
operator here.
Copy code
fun getData(): Flow<Pair<String?, String?>> {
    val flow1 = channel1.asFlow()
        .flowOn(dispatcher)
    val flow2 = channel2.asFlow()
        .flowOn(dispatcher)
    return flow1.combine(flow2) { data1, data2 ->
            data1 to data2
        }
        .flowOn(dispatcher)
}

suspend fun addData1(value: String?) = withContext(dispatcher) {
    channel1.send(value)
}

@Test
fun `receives data1`() = runBlocking {
    exampleDataSource.getData()
        .test {
            assertEquals(null to null, expectItem())

            exampleDataSource.addData1("data1")
            assertEquals("data1" to null, expectItem())

            cancel()
        }
}
So far I've been able to make the tests pass by removing the
flowOn
operator or by changing the injected dispatcher to
Dispatchers.Unconfined
Question Why is this happening? Could anyone explain me why using
flowOn
operator is causing this? I may be using this wrong coming from Rx word 😕 repository url https://github.com/AdamGrzybkowski/coroutineTestingProblem
t

tseisel

03/27/2020, 2:18 PM
When using
TestCoroutineDispatcher
, you need to also use `runBlockingTest`: https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-test/README.md#providing-an-explicit-testcoroutinedispatcher I don't think you can use
TestCoroutineDispatcher
with
runBlocking
.
a

Adam Grzybkowski

03/27/2020, 10:17 PM
yup, you are probably right that I shouldn't use
TestCoroutineDispatcher
with
runBlocking
but adding
runBlockingTest
will not fix the tests. And still for me the most weird behavior is that removing the
flowOn
operator from
combine
is fixing the tests.
w

wasyl

03/29/2020, 11:21 AM
@Adam Grzybkowski One thing that fixes the tests is also switching from
runBlocking
to
testCoroutineDispatcher.runBlockingTest
. I also have no idea why, but it seems to work
2 Views