Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

355
Views
Mocking LiveData object in Android ViewModel using Mockito

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.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!