soiXam
soiXam

Reputation: 99

How to Properly Test Coroutine Delays in Kotlin with advanceTimeBy vs delay?

I’m writing unit tests for a function fetchData() in my class that simulates a network API call and sets a flag fetchDataFinished to true:

class UnderTest (
    mainDispatcher: CoroutineDispatcher = Dispatchers.Main
) {
    private val scope = CoroutineScope(CoroutineName("UnderTestScope") + mainDispatcher)

    var fetchDataFinished: Boolean = false

    fun fetchData() = scope.launch {
        delay(2000) //fake api call
        fetchDataFinished = true
    }
}

In my unit test, I want to assert that fetchDataFinished is true after the API call simulation. Here is my test function:

internal class UnderTestTest {
    @get:Rule
    val coroutineRule = MainDispatcherRule()

    private lateinit var underTest: UnderTest

    @Before
    fun setUp() {
        underTest = UnderTest(coroutineRule.testDispatcher)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun test1() = runTest {
        underTest.fetchData()
        advanceTimeBy(2001)
//        delay(2001) //also work
        assertEquals(true, underTest.fetchDataFinished)
    }
}

Both advanceTimeBy(2001) and delay(2001) in my test function seem to work and pass the test. My question is:

Which method should I use for testing coroutine delays, and why?

Upvotes: 0

Views: 72

Answers (0)

Related Questions