Hello everyone, can anyone help me with this test ...
# android
l
Hello everyone, can anyone help me with this test case?
Copy code
@Test
fun `Should get images and add to list`() = runBlockingTest {
    coEvery { getPhotosUseCase(any()) } returns flow { emit(Source.Success(GetImagesTestData.DOMAIN_RESPONSE)) }

    //viewModel.getImages()

    coVerify(exactly = 1) { getPhotosUseCase(any()) }
    confirmVerified(getPhotosUseCase)
    assertEquals(GetImagesTestData.DOMAIN_RESPONSE, viewModel.photos.toList())
}
This test keeps failing because it says that viewModel.photos.ToList() is empty, therefore not equal to the expected result. The test will only pass if call the viewModel.getImages() method inside the test block, but this method is already being called in the init{} block of the viewModel. Can anyone help me understand why this is happening?
j
Does viewModel.getImages() call getPhotosUseCase()? If so, then it looks like the init for your viewModel is being called in the setup for your tests so it’s happening before you’ve mocked the getPhotosUseCase response.
l
yes, getImages() calls the use case if the request fails and the user wants to try again for example
so it's basically:
init {
this.getImages() } fun getImages() { viewModelScope.launch { callUseCase() ....} }
j
ok, that’s what I was assuming. In that case, your photos aren’t getting set in your test because your getPhotosUseCase isn’t mocked when init is called in the setup method (\@Before annotated method) . They get set when you call getImages manually because that’s after you’ve mocked the response at the beginning of your test
I would probably recreate my viewModel object in this test case after I’ve mocked the response I want here which will then call getImages in the init. This verifies the init of your viewModel is doing what you expect
l
I tried this approach but it didn't work as well
Copy code
@Test
fun `Should set viewstate to error if get images succeeds but returns a null object`() =
    runBlocking {
        coEvery { getPhotosUseCase(any()) } returns flow { emit(Source.Success(null)) }
        viewModel = PhotoListViewModel(getPhotosUseCase, ratePhotosUseCase)
        coVerify(exactly = 1) { getPhotosUseCase(1) }
        confirmVerified(getPhotosUseCase)
        assertTrue(viewModel.screenState.value is ViewState.Error)
    }
s
You can debug unit tests as well with break points. Or you can do the good ol
println()
debugging to get a better sense of what is going on in your setup.