繁体   English   中英

如何在 mockk kotlin 中模拟 LiveData

[英]How to mock LiveData in mockk kotlin

嘿,我在我的项目中使用 mockk 库。 我试图模拟 MutableLiveData,但它总是给我 null 值。 有人可以指导我如何以正确的方式去做。

假设我有一个 function

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

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

我正在尝试测试

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

当我运行测试时它给了我这个

Expected : true
Actual   :null

依赖关系

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"

一些对我有帮助的提示:

  1. 在 runBlockingTest 中运行您的测试

  2. 在发送断言 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. 将此添加到测试 Class
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
  1. 声明private val testCoroutineDispatcher = TestCoroutineDispatcher()并将其添加到 setUp() Dispatchers.setMain(testCoroutineDispatcher)

  2. 将此添加到 tearDown() Dispatchers.resetMain()

  3. 在您的测试 class 声明之前添加这个 @ExperimentalCoroutinesApi

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM