Android how to test LiveData in the test scope

Viewed 206

How to test a LiveData observer in the scope test.

I have a fragment that is testing observing LiveData, for simplicity I'm showing the function with the observer.

  fun liveDataObserver() {
        viewModel.scoreLiveData.observe(viewLifecycleOwner, {
            Log.i("Practice", "New score is $it")
        } )
    }

I use Robolectric to launch the fragment in the test scope.

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

    }

The test returns the following errors

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.

I've tried implementing a shadow class for the Main Looper. Adding scenario states.

Here my testing dependencies if that is helpful

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

You need to add a test rule. Add this as class variable in your test class.

@get:Rule
var rule: TestRule = InstantTaskExecutorRule() 
Related