'How to mock LiveData in mockk kotlin

Hey I am using mockk library in my project. I am trying to mock MutableLiveData, but it always give me null value. Can someone guide me how to do in proper way.

Suppose I have one function

var dataLiveData = MutableLiveData<Boolean>()
 val currentDeviceTypeLiveData = MutableLiveData<Boolean>()

internal fun handleDataResponse() {
        dataLiveData.postValue(true)
        currentDeviceTypeLiveData.postValue(true)
}

I am trying to test

@Test
fun `handleDataResponse - Handle connection success `() {
    // STUBBING
    // EXECUTION
    viewModel.handleDataResponse()
    // VERIFICATION
    assertEquals(true, viewModel.dataLiveData.value)
    assertEquals(true, viewModel.currentDeviceTypeLiveData.value)
}

It gives me this when I run the test

Expected : true
Actual   :null

dependencies

testImplementation 'androidx.arch.core:core-testing:2.1.0'
testImplementation "io.mockk:mockk:1.12.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0"


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source