Android: Testing ViewModel with coroutines and states

31 Views Asked by At

I have been trying to understand how testing of ViewModel work in Android. I have the following view model class:

@HiltViewModel
class AllLaunchesViewModel @Inject constructor(
    private val allLaunchesUseCase: GetAllLaunchesUseCase
) {
    var allLaunchesToDisplay = mutableStateListOf<LaunchItemToDisplay>()
        private set

    fun loadAllLaunches() {
        viewModelScope.launch {
            allLaunchesUseCase().collect {
                allLaunchesToDisplay = it
            }
        }
    }
}

And following are my Test functions:

class AllLaunchesViewModelTest {
    private lateinit var viewModel: AllLaunchesViewModel

    @Before
    fun setup() {
        val launchesRepo = FakeLaunchesRepo()
        viewModel = AllLaunchesViewModel(
            GetAllLaunchesUseCase(launchesRepo)
        )
        viewModel.onUserEvent(AllLaunchesUserEvent.LoadAllLaunches)
    }

    @Test
    fun `check if response parsing is working, should return true for expected array size 3`() {
        val launches = viewModel.allLaunchesToDisplay.toList()
        assertEquals(3, launches.size)
    }
}

But my test is continuously failing because my loadAllLaunches() function is starting a new coroutine and my test function doesn't wait for it to finish. It goes on to check the size of my list which would have data if it lets the coroutine to finish its work. But since it doesn't wait, the size is returned 0 and my test fails.

How can I tell this test to wait for the coroutine inside my viewModel to finish before checking the size of list?

I have already experimented with TestCoroutineScope and TestCoroutineDispatcher and also StandardTestDispatcher but they have not done anything.

Any help would be highly appreciated.

0

There are 0 best solutions below