如何使用 Robolectric 运行具有 LiveData 观察器的片段测试

问题描述

如何在包含使用 Robolectric 的 LiveData 观察者的测试范围内启动片段。

我的片段正在观察来自 viewmodel 的 liveData。如果我删除这部分代码,测试就会运行。


fun observerData() {

    viewmodel.MyLiveData.observe(viewLifecycleOwner,Observer {
        ...
    })
}

测试使用片段场景来启动片段。

@RunWith(RobolectricTestRunner::class) 
class MyFragmentTest {

    @Test
    fun mytest() {
         val viewmodel: Myviewmodel = mock(Myviewmodel::class.java)
         val scenario = launchFragmentInContainer(
             factory = MainFragmentFactory(viewmodel),fragmentArgs = null,themeResId = R.style.Theme_MyTheme
         )
    }
}

测试返回以下错误

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.

我已经尝试将主循环器设置为偶像,但仍然出现相同的错误

解决方法

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

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

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