简体   繁体   English

Android如何在测试中测试LiveData scope

[英]Android how to test LiveData in the test scope

How to test a LiveData observer in the scope test.如何在 scope 测试中测试 LiveData 观察者。

I have a fragment that is testing observing LiveData, for simplicity I'm showing the function with the observer.我有一个片段正在测试观察 LiveData,为简单起见,我向观察者展示了 function。

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

I use Robolectric to launch the fragment in the test scope.我使用 Robolectric 启动测试 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.我已经尝试为 Main Looper 实现一个影子 class 。 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"

You need to add a test rule.您需要添加测试规则。 Add this as class variable in your test class.将此作为 class 变量添加到您的测试 class 中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM