how can i unit test flows? the following never com...
# coroutines
m
how can i unit test flows? the following never completes
Copy code
@Test
    fun listCanBeObserved() = runBlocking {
        dao.insert(thing)

        val data: List<Thing> = dao.observeAll().single()
        val expected = Thing()
        assertEquals(expected, data)
    }
but if I manually collect each emission I can see the assertion is hit successfully in debug mode
Copy code
fun listCanBeObserved() = runBlocking {
        dao.insert(thing)

        val data: List<Thing> = dao.observeAll().collect {
            val expected = Thing()
            assertEquals(expected, data)
        }
    }
but then the test will never complete
d
Use
first()
An observer observes forever, so the flow will never complete. Just get the first emission if that's what you need.
m
that’s not the reason the test won’t complete. copy-paste error but
expected
is
listOf(thing)
ah i see, first is a terminal operator. thanks
single()
is kind of misleading then, i’d expect it to do the same thing
d
It kinda does, but it confirms that the flow only emits one item.
m
i see. thanks for your help