jean
01/17/2023, 11:26 AMUnconfinedTestDispatcher
and not with StandardTestDispatcher
?
private val testCoroutineDispatcher = UnconfinedTestDispatcher()
private val testCoroutineScope = TestScope(testCoroutineDispatcher)
private val testContext = ApplicationProvider.getApplicationContext<Context>()
private val sessionRepository: SessionRepository =
PersistentSessionRepository(
DataStoreFactory.create(
serializer = SessionPreferencesSerializer,
scope = testCoroutineScope,
produceFile = { testContext.preferencesDataStoreFile("test-session-preferences") }
),
routeRepository = routeRepository,
)
@Test
fun sessionShouldInitiallyBeNull() = runTest(testCoroutineDispatcher, 5000) {
assertNull(sessionRepository.session())
}
When I use StandardTestDispatcher
I get this error :
After waiting for 60000 ms, the test coroutine is not completing
kotlinx.coroutines.test.UncompletedCoroutinesError: After waiting for 60000 ms, the test coroutine is not completing
Dmitry Khalanskiy [JB]
01/17/2023, 11:31 AMTestScope
and not call runTest
on it. runTest(testCoroutineDispatcher, 5000)
→ testCoroutineScope.runTest
jean
01/17/2023, 11:44 AMtestCoroutineScope.runTest
then I get this :
Channel was closed
kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed
Dmitry Khalanskiy [JB]
01/17/2023, 11:45 AMtestCoroutineScope
in runTest
that exception was just swallowed.jean
01/17/2023, 11:47 AMoverride suspend fun session() = dataStore.data
.firstOrNull()
?.let { wrapperToSession(it) }
What would cause a channel to close with this? I’m just trying to get the current value of a DataStore
on which I don’t have controlDmitry Khalanskiy [JB]
01/17/2023, 11:51 AMDataStore
is, maybe someone else can answer this. From what I see, the test code itself doesn't fail (or not using testCoroutineScope
in runTest
wouldn't matter). Rather, something else that uses this scope fails with the exception. I suggest looking more closely at the stacktrace to find the specific code that fails.Sam
01/17/2023, 11:54 AMscope = testCoroutineScope.backgroundScope
to the DataStoreFactory
would help?Dmitry Khalanskiy [JB]
01/17/2023, 11:55 AMbackgroundScope
helps with the test hanging due to background work being executed, but this is the case of the producer failing for some reason, so the consumer times out when waiting.jean
01/17/2023, 11:55 AMstacktrace
and turned out I forgot to also use testCoroutineScope.runTest
on a @After
test function that clears my store.
After updating it, I have another issue : Only a single call to runTest can be performed during one test
Dmitry Khalanskiy [JB]
01/17/2023, 11:58 AMrunBlocking
in @After
. Or maybe it's possible not to use coroutines in @After
at all.jean
01/17/2023, 11:58 AM@Test
fun sessionShouldInitiallyBeNull() = testCoroutineScope.runTest {
assertNull(journeySessionRepository.journeySession())
journeySessionRepository.clearSession()
}