Hello everyone! I am having some problems unit tes...
# android
e
Hello everyone! I am having some problems unit testing coroutines, specifically when I have one coroutine doing stuff in a while(true) loop with a delay, and a second coroutine collecting from SharedFlow. The SharedFlow doesn't get called in tests. Here's a code example, using mockk library in tests:
Copy code
class MyClass(dispatcher: CoroutineDispatcher = Dispatchers.Default) {
        private val scope = CoroutineScope(dispatcher)

        fun start() {
            scope.launch {
                while (true) {
                    // do stuff
                    delay(1000L)
                }
            }
            scope.launch {
                OtherObject.someSharedFlow.collect {
                    ThirdObject.doSomeStuff()
                }
            }
        }
    }

    private val testSharedFlow = MutableSharedFlow<SomeEvent>()
    
    @Test
    fun someTest() = runTest {
        mockkObject(OtherObject)
        every { OtherObject.someSharedFlow } returns testSharedFlow.asSharedFlow()
        
        mockkObject(ThirdObject)
        every { ThirdObject.doSomeStuff() } answers {}
        
        val myClass = MyClass(StandardTestDispatcher(testScheduler))
        myClass.start()

        testSharedFlow.emit(SomeEvent()).also {
            verify { ThirdObject.doSomeStuff() } // this fails
        }
        
        unmockkObject(ThirdObject)
        unmockkObject(OtherObject)
    }