Search code examples
androidunit-testingkotlinmockitoandroid-viewmodel

lateinit property fakeAuthRepository has not been initialized unit testing


I am using unit testing when I run test I am getting following exception

ateinit property fakeAuthRepository has not been initialized kotlin.UninitializedPropertyAccessException: lateinit property fakeAuthRepository has not been initialized

below my ViewModel test where test giving an exception

internal class SignInViewModelTest{
    private val _login =  MutableStateFlow<UiStateObject<SignInResponse>>(UiStateObject.EMPTY)

         @Mock
        lateinit var backendApi:BackendApi

    lateinit var fakeAuthRepository: FakeAuthRepository
    lateinit var authRepository: AuthRepository
    private lateinit var viewModel: SignInViewModel
    @Before
    fun setUp() {

        MockitoAnnotations.initMocks(this)
        fakeAuthRepository = FakeAuthRepository(backendApi)
        authRepository = AuthRepository(backendApi)
        viewModel = SignInViewModel(authRepository)

    }

    var login = _login

    @Test
    fun `testing repository`() = runBlockingTest {

        val fake = fakeAuthRepository.login("[email protected]", "12345678", "android", "123455")
        val real = authRepository.login("[email protected]", "12345678", "android", "123455")
        assertEquals(fake, real)


    }



}

Solution

  • @Before is junit4 annotation.

    If you are using junit5 you have to replace it with @BeforeEach.