问题描述
我正在尝试在我的 RecyclerView 上运行单元测试。对于我的第一次测试,我想看看 RecyclerView 是否显示。
@RunWith(RobolectricTestRunner::class)
class WordListFragmentTest {
// Executes task sin the Architecture component in the same thread.
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var scenario: FragmentScenario<WordListFragment>
private lateinit var viewmodel: Mainviewmodel
val word = Word("Word")
@Before
fun setup() {
viewmodel = mock(Mainviewmodel::class.java)
scenario = launchFragment(
factory = MainFragmentFactory(viewmodel),fragmentArgs = null,themeResId = R.style.Theme_Words,initialState = Lifecycle.State.RESUMED
)
}
@Test
fun `recyclerView displayed`() {
onView(withId(R.id.recyclerView))
.check(matches(isdisplayed()))
}
运行测试后出现以下错误。
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.
这似乎与提交片段中的列表的 LiveData 观察者有关。如果我注释掉提交功能,测试将运行。
碎片。
class WordListFragment(private val viewmodel: Mainviewmodel) : Fragment() {
...
private fun submitList() {
viewmodel.wordList.observe(viewLifecycleOwner,{
it?.let {
rvAdapter.submitList(it)
}
})
}
}
Mianviewmodel
class Mainviewmodel @Inject constructor(
var repository: IWordRepository,@Iodispatcher var iodispatcher: Coroutinedispatcher
) : viewmodel() {
var wordList: LiveData<List<Word>> = repository.allWords
...
}
This link 表示 Robolectric 将默认为 LooperMode.LEGACY 行为,但这可以通过将 @LooperMode(NewMode) 注释应用于测试包、测试类或测试方法,或通过 'robolectric.LEGACY. looperMode' 系统属性。我在运行测试时仍然遇到同样的错误。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)