微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。