如何在范围测试中测试LiveData观察者。
我有一个测试观察LiveData的片段,为了简单起见,我正在向观察者展示这个函数。
fun liveDataObserver() {
viewModel.scoreLiveData.observe(viewLifecycleOwner, {
Log.i("Practice", "New score is $it")
} )
}我使用Robolectric在测试范围内启动这个片段。
@RunWith(RobolectricTestRunner::class)
class ScoreKeeperFragmentTest {
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun testOne() = runBlockingTest {
val viewModel: MyViewModel = mock(MyViewModel::class.java)
scenario = launchFragmentInContainer(
factory = MainFragmentFactory(viewModel),
fragmentArgs = null,
themeResId = R.style.Theme_TDDScoreKeeper,
initialState = Lifecycle.State.RESUMED
)
}测试返回以下错误
java.lang.Exception: Main looper has queued unexecuted runnables. This might be the cause of the test failure. You might need a shadowOf(getMainLooper()).idle() call.我尝试为主活套实现一个影子类。添加场景状态。
这里我的测试依赖关系(如果这是有用的)
// Test
testImplementation 'androidx.arch.core:core-testing:2.1.0'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3'
testImplementation "androidx.test.ext:junit-ktx:1.1.2"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.3"
testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
testImplementation 'junit:junit:4.13.2'
testImplementation 'androidx.test.espresso:espresso-core:3.3.0'
testImplementation "org.robolectric:robolectric:4.5.1"
testImplementation "org.mockito:mockito-android:2.28.2"
// Testing Fragments
debugImplementation "androidx.fragment:fragment-testing:1.3.2"发布于 2022-09-16 20:19:59
您需要添加一个测试规则。将其作为类变量添加到测试类中。
@get:Rule
var rule: TestRule = InstantTaskExecutorRule() https://stackoverflow.com/questions/67084843
复制相似问题