Android如何在测试范围内测试LiveData

问题描述

如何在范围测试中测试 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.

我尝试为 Main Looper 实现一个影子类。 添加场景状态。

如果有帮助,这里是我的测试依赖项

    // 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"

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)