https://kotlinlang.org logo
#mockk
Title
# mockk
v

Vivek Modi

01/26/2022, 10:38 PM
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

Nikita Voloshin

01/26/2022, 11:19 PM
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
4 Views