Hi All :android-wave: , How to test this `updateAc...
# coroutines
a
Hi All 👋 , How to test this
updateAccount()
method?
Copy code
fun updateAccount() {
    coroutineScope.launch {
        startLoading()
        val isAccountUpdated = updateAccountUseCase()
        if (isAccountUpdated) {
            navigator.navigateUp()
        } else {
            completeLoading()
            // TODO: Show Error
        }
    }
}

// For context
fun startLoading() {
    isLoading = true
    refreshSignal.tryEmit(Unit)
}
fun completeLoading() {
    isLoading = false
    refreshSignal.tryEmit(Unit)
}
More details in thread 🧵 . Can anyone please help thank you color .
This test works,
Copy code
@Test
fun `updateAccount when updateAccountUseCase returns true`() = testScope.runTest {
    whenever(updateAccountUseCase()).thenReturn(true)

    SUT.refreshSignal.test {
        SUT.updateAccount()

        assertEquals(Unit, awaitItem())
        assertEquals(true, SUT.isLoading)
        expectNoEvents()
    }

    verify(navigator).navigateUp()
}
But this fails,
Copy code
@Test
fun `updateAccount when updateAccountUseCase returns false`() = testScope.runTest {
    whenever(updateAccountUseCase()).thenReturn(false)

    SUT.refreshSignal.test {
        SUT.updateAccount()

        assertEquals(Unit, awaitItem())
        assertEquals(true, SUT.isLoading) // This assertion fails as the isLoading is reset by this time (my guess)
        assertEquals(Unit, awaitItem())
        assertEquals(false, SUT.isLoading)
        expectNoEvents()
    }
}
Testing coroutine scope used.
Copy code
private val testDispatcher = UnconfinedTestDispatcher()
private val testScope = TestScope(testDispatcher)
The code sets a loader and emits a value in a MutableSharedFlow, And then resets if only if there is any error (updateAccountUseCase returns false). If updateAccountUseCase returns true, a navigation event is triggered.
Added question in StackOverflow with more details. https://stackoverflow.com/q/79034315/9636037 Can anyone please help gratitude thank you
d
Please see https://github.com/Kotlin/kotlinx.coroutines/issues/3939 In essence, the test correctly shows that, if
updateAccountUseCase
immediately returns
false
, the two emissions will be conflated into one. Insert a delay into the mocked method to simulate that the call does not finish immediately, this will make the test pass.