Hey I am testing Live Data value. When I am mockin...
# mockk
v
Hey I am testing Live Data value. When I am mocking it giving me null pointer expection.
Copy code
internal fun handleDataResponse() {
        dataLiveData.postValue(true)
        currentDeviceTypeLiveData.postValue(true)
}
test
Copy code
@Test
fun `handleDataResponse - Handle connection success `() {
    // STUBBING
    // EXECUTION
    viewModel.handleDataResponse()
    // VERIFICATION
    assertEquals(true, viewModel.dataLiveData.value)
    assertEquals(true, viewModel.currentDeviceTypeLiveData.value)
}
Copy code
Expected : true
Actual   :null
n
It would be better if you provide complete example including mock creation and stubbing. But anyway, if you want your mocked objects to behave as original objects you should either use
spyk
or stub method call with
callOriginal()
. Otherwise, mock will either fail or return
null
based on whether it is relaxed or not. So, make sure your stubbing block contains at least this:
Copy code
every { viewModel.dataLiveData.postValue(any()) } answers { callOriginal() }
Then, based on your mock creation logic you might need to also stub
viewModel.dataLiveData
itself in order to stub
get/set
for live data