[英]How to mock LiveData in mockk kotlin
Hey I am using mockk library in my project.嘿,我在我的项目中使用 mockk 库。 I am trying to mock MutableLiveData, but it always give me null value.我试图模拟 MutableLiveData,但它总是给我 null 值。 Can someone guide me how to do in proper way.有人可以指导我如何以正确的方式去做。
Suppose I have one function假设我有一个 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"
Some tips that helped me:一些对我有帮助的提示:
run your test in runBlockingTest在 runBlockingTest 中运行您的测试
create variable for live data before sending in assert function在发送断言 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)
}
}
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
Declare private val testCoroutineDispatcher = TestCoroutineDispatcher()
and Add this in setUp() Dispatchers.setMain(testCoroutineDispatcher)
声明private val testCoroutineDispatcher = TestCoroutineDispatcher()
并将其添加到 setUp() Dispatchers.setMain(testCoroutineDispatcher)
Add this in tearDown() Dispatchers.resetMain()
将此添加到 tearDown() Dispatchers.resetMain()
Add this before your test class declaration @ExperimentalCoroutinesApi在您的测试 class 声明之前添加这个 @ExperimentalCoroutinesApi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.