2

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"
Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127

1 Answers1

1

Some tips that helped me:

  1. run your test in runBlockingTest

  2. create variable for live data before sending in assert function

@Test
fun `handleDataResponse - Handle connection success `() { 
 runBlockingTest{

    // STUBBING
    // EXECUTION
    viewModel.handleDataResponse()
    val dataLiveData = viewModel.dataLiveData.value
    val currentDeviceTypeLiveData = viewModel.currentDeviceTypeLiveData.value
    // VERIFICATION
    assertEquals(true, dataLiveData)
    assertEquals(true, currentDeviceTypeLiveData)
 }
}
  1. Add this in test Class
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
  1. Declare private val testCoroutineDispatcher = TestCoroutineDispatcher() and Add this in setUp() Dispatchers.setMain(testCoroutineDispatcher)

  2. Add this in tearDown() Dispatchers.resetMain()

  3. Add this before your test class declaration @ExperimentalCoroutinesApi