Hi all :android-wave: , How to fix this coroutines...
# coroutines
a
Hi all 👋 , How to fix this coroutines unit test?
Copy code
No value produced in 3s
Details in thread 🧵 .
Test Code
Copy code
class UsecaseTest {
    private val testDispatcher = UnconfinedTestDispatcher()
    private val testScope = TestScope(testDispatcher)
    private lateinit var SUT: Usecase

    @Before
    fun setUp() {
        SUT = Usecaseimpl(
            coroutineScope = testScope,
        )
    }

    @Test
    fun refresh() = testScope.runTest {
        turbineScope {
            val receiver = SUT.refreshSignal.testIn(
                scope = testScope,
            )
            SUT.refresh()
            assertEquals(
                Unit,
                receiver.awaitItem(),
            )

            receiver.awaitComplete()
        }
    }
}
SUT code
Copy code
class UsecaseImpl(
    private val coroutineScope: CoroutineScope,
): Usecase {
    override val refreshSignal: MutableSharedFlow<Unit> = MutableSharedFlow(
        replay = 0,
        extraBufferCapacity = 1,
    )

    override fun refresh() {
        refreshSignal.tryEmit(Unit)
    }
}
As mentioned in Turbine Docs, I have tried with
Copy code
receiver.cancel()
receiver.awaitComplete()
receiver.awaitError()
And also by replacing
testScope
with
backgroundScope
. >
testIn
cannot automatically clean up its coroutine, so it is up to you to ensure that the running flow terminates. Use `runTest`'s
backgroundScope
, and it will take care of this automatically. Otherwise, make sure to call one of the following methods before the end of your scope: > •
cancel()
> •
awaitComplete()
> •
awaitError()
> Otherwise, your test will hang.
Changed to this and it worked.
Copy code
SUT.refreshSignal.test {
            SUT.refresh()
            assertEquals(
                Unit,
                awaitItem(),
            )
        }
I am not able to make it work with
turbineScope
. Can anyone please help share what change is required for
turbineScope
thank you color?
d
Have you tried StandardTestDispatcher?
Also I think your setup is a bit over engineered. You can use something like:
Copy code
fun test() = runTest(YourTestDispatcher()) {
    val tested = YourUseCase(scope = backgroundScope)
    
    tested.flow.test {
        awaitItem()
        ...
    }
}
a
I have tried standard dispatcher, I had other issues with that.
The above code still uses test lambda and not turbine scope lambda. I have also tried the background scope, but it didn't work.
d
The
.test
is the turbine lambda.
a
Yes, but not turbine scope lambda. The one used to test multiple flows.
d
Ah I didnt see your working example. I havent used turbineScope yet.