首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在测试范围内测试LiveData

如何在测试范围内测试LiveData
EN

Stack Overflow用户
提问于 2021-04-14 02:47:08
回答 1查看 242关注 0票数 1

如何在范围测试中测试LiveData观察者。

我有一个测试观察LiveData的片段,为了简单起见,我正在向观察者展示这个函数。

代码语言:javascript
复制
  fun liveDataObserver() {
        viewModel.scoreLiveData.observe(viewLifecycleOwner, {
            Log.i("Practice", "New score is $it")
        } )
    }

我使用Robolectric在测试范围内启动这个片段。

代码语言:javascript
复制
@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
        )

    }

测试返回以下错误

代码语言:javascript
复制
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.

我尝试为主活套实现一个影子类。添加场景状态。

这里我的测试依赖关系(如果这是有用的)

代码语言:javascript
复制
    // 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"
EN

回答 1

Stack Overflow用户

发布于 2022-09-16 20:19:59

您需要添加一个测试规则。将其作为类变量添加到测试类中。

代码语言:javascript
复制
@get:Rule
var rule: TestRule = InstantTaskExecutorRule() 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67084843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档