Why does my stateflow not change in my unit tests?

220 Views Asked by At

I have a state flow that is init to true

private val isCreateProfileDisabledData = MutableStateFlow(true)
    
val isCreateProfileDisabled = isCreateProfileDisabledData.asStateFlow()

And then this function that runs on init that looks like

fun fetchCreateProfileDisabled() {
        viewModelScope.launch {
            organizationRepository.getAllOrganizations().whenOk { 
                ...
                val isProfileCreationDisabled = (some work to figure out if true or false)
                isCreateProfileDisabledData.value = isProfileCreationDisabled
            }
        }
    }

And this code actually seems to work in my app. But during unit testing, the value never changes.

My test looks like this

    @Test
    fun `Some Test`() = runBlockingTest {
        val mockOrg = Organization(
             isMobileProfileCreationDisabled = false
        )

        viewModel.fetchCreateProfileDisabled()
        whenever(organizationRepository.getAllOrganizations()).thenReturn(
            BaseResult.Ok(listOf(mockOrg))
        )

        viewModel.isCreateProfileDisabled.test {
            assertEquals(expectMostRecentItem(), false)
        }
    }

Basically when that isMobileProfileCreationDisabled value is false, then my stateflow should also be false. But it is always true.

I did try using awaitItem() instead of expectMostRecentItem() with the same result. And I also tried moving fetchCreateProfileDisabled() to inside of the turbine test before the assertEquals.

I set up some break points, and it never seems to hit anything after

  organizationRepository.getAllOrganizations().whenOk {

but I have no idea why that is. Shouldn't that not happen since I am using whenever to mock the result?

0

There are 0 best solutions below