0

I have a question related to Unit testing in android. The app is written in Kotlin, MVVM architecture, Dagger-Hilt, Room, etc… I have written all the tests for Room DAOs, according to official docs. I have created fake repositories so I can test some Managers/Helpers (these classes encapsulate logic I have to reuse in many ViewModels) that handle business logic. Now I need to test ViewModels which have these Managers/Helpers as dependencies. I don’t want to fall into trap of re-testing the same code all over again, the question is how to test ViewModels? Should I only test the parameters that are passed to functions in these Managers/Helpers, and write assertions for that, or what to do?

Thanks in advance!

Daguna
  • 141
  • 8

1 Answers1

0

That is what mocks are for. You should test only logic of ViewModel ignoring logic inside Managers/Helpers. Everything else should be mocked/faked:

@Test
fun `invalid login`() {
    runBlocking {

        //prepare
        val validator = mock<Validator> {
            on { errorFor(any()) }
                    .thenReturn("Something wrong")
        }
        val authNavigator = spy(loginNavigator)

        val tracker = spy(ActionsTracker(mock()))
        val trackers = Trackers(tracker, ViewsTracker(mock()), ClicksTracker(mock()), ImpressionsTracker(mock()))

        assertViewModel(
                validation = AuthViewModel.LoginValidation(validator, validator),
                authNavigator = authNavigator,
                trackers = trackers
        ) {
            email.set("test")
            password.set("test")

            //assert
            assertNull(emailError.get())
            assertNull(passwordError.get())

            //act
            login()

            //assert
            assertNotNull(emailError.get())
            assertNotNull(passwordError.get())
            verify(authNavigator, never()).navigateToHome()
            verify(tracker, never()).userPropertiesChanged(any(), any())
        }
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mike
  • 2,547
  • 3
  • 16
  • 30