0

Hi I am trying to write some unit test cases for the Stateflow and Flow in Kotlin Multiplatform,

My requirement is

val loader = MutableStateFlow(false)

    suspend fun fetchBugs(bugsParams: BugsApiRequestParams) {
        val responseObject = remoteDataSource.getBugsFromTheServer(bugsParams)
        loader.value = true
        if (responseObject.isResponseArrayInitialized()) {
            val bugs = mapper.mapBugs(responseObject, bugsParams.portalId, bugsParams.projectId)
            localDataSource.insertOrUpdate(bugs)
        }
        loader.value = false
    }

I want to check all the values emitted by the flow in the fetchBugs call, and I have tried to convert the flow into a list but of no use

@Test
fun makeTheLoaderToTrueWhenBeforeItHitServer()= runBlocking{
    val repository = mockSuccessfulCase()
    repository.fetchBugs(bugsParams)
    assertEquals(false , repository.loader.first())
}

Is there any way to check it? Thanks in advance :)

shadowsheep
  • 14,048
  • 3
  • 67
  • 77

1 Answers1

1

This is the go-to library for testing Flows:

https://github.com/cashapp/turbine

@Test
fun makeTheLoaderToTrueWhenBeforeItHitServer()= runBlocking{
    val repository = mockSuccessfulCase()
    repository.loader.test {
      assertEquals(false, expectItem())
      assertEquals(true, expectItem())
      cancelAndIgnoreRemainingEvents()
    }
    repository.fetchBugs(bugsParams)
}

Install it like this

repositories {
  mavenCentral()
}
dependencies {
  testImplementation 'app.cash.turbine:turbine:0.4.0'
}
shredder
  • 1,438
  • 13
  • 12
  • Does this work with multithreaded native coroutines on iOS? Thank you :) – beretis May 17 '21 at 12:33
  • Probably not - KMP basically has a big global freeze flag for threading. I would avoid all multi threading on KMP as a general rule. – shredder Aug 03 '21 at 13:22