Mocking LiveData object in Android ViewModel using Mockito

Viewed 1710

I have a ViewModel look like this.

class SignInViewModel(private val requestDataUseCase: RequestDataUseCase) : ViewModel() {

  ...
  var isLoading = MediatorLiveData<Boolean>()
  ...

  fun requestData(id: String) {
        requestDataUseCase(id).let { liveData ->
            isLoading.value = true
            isLoading.addSource(liveData) {
                it?.either(this::onSuccess, this::handleError)
                isLoading.removeSource(liveData)
                isLoading.value = false
            }
        }
    }
...

}

My test class

class SignInViewModelTest {
        private lateinit var signInViewModel: SignInViewModel
        @Mock private lateinit var requestDataUseCase: RequestDataUseCase
        private val dataResponse: MutableLiveData<String> = MutableLiveData()

        @Before
        fun setUp() {
            signInViewModel = SignInViewModel(requestDataUseCase)
        }

        @Test
        fun testRequestData() {
            `when`(requestDataUseCase(any(), any())).thenReturn(dataResponse)
            //trying to call
            fun requestData("123456")
        }
}

The problem is I got NullPointerException on isLoading variable in SignInViewModel class.

It's the variable that controls ProgressBar in the XML layout.

So my question is how can I mock the isLoading variable?

Or are there any suggestion on how should I create a test for this scenario?

Thank you in advance.

0 Answers
Related