Main Looper queued unexecuted runnables

2.7k views Asked by At

I'm trying to run a unit test on my RecyclerView. For my first test, I want to see if the RecyclerView is displayed.

@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()))
    }

After running the test I get the following error.

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.

This appears to be related to LiveData observer that submits the list in the fragment. If I comment out the submit function the test will run.

The Fragment.

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 states Robolectric will default to LooperMode.LEGACY behavior, but this can be overridden by applying a @LooperMode(NewMode) annotation to a test package, test class, or test method, or via the 'robolectric.looperMode' system property. I'm still experiencing the same error when I run my test.

0

There are 0 answers