【问题标题】:how to use Espresso with Kotlin Flow?如何在 Kotlin Flow 中使用 Espresso?
【发布时间】:2021-02-12 13:11:42
【问题描述】:

在我的应用中,我使用 Kotlin Flow。在我使用 EspressoIdlingResource.increment() 的挂起函数之前,它不适用于 Kotlin Flow。如何解决这个问题?

【问题讨论】:

  • EspressoIdlingResource.increment() 应该告诉框架等到某些后台操作完成。但我使用 Flows 和 Espresso 无需等待即可立即完成检查

标签: android-espresso android-testing kotlin-flow


【解决方案1】:

我已经复制了您的问题,然后解决了问题。

我需要在你的 gradle 中添加 implementationandroidTestImplementation 中的 espresso-idling-resource 库:

implementation 'androidx.test.espresso:espresso-idling-resource:3.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.3.0'

这样我可以在我的项目中创建CountingIdlingResourceSingleton 对象:

object CountingIdlingResourceSingleton {

    private const val RESOURCE = "GLOBAL"

    @JvmField val countingIdlingResource = CountingIdlingResource(RESOURCE)

    fun increment() {
        countingIdlingResource.increment()
    }

    fun decrement() {
        if (!countingIdlingResource.isIdleNow) {
            countingIdlingResource.decrement()
        }
    }
}

然后,当您希望测试等待时,您应该在代码中调用它,在我的情况下,它位于显示的第一个片段的 onViewCreated() 中:

CountingIdlingResourceSingleton.increment()

当第一个流元素到达时,我刚刚调用了:

CountingIdlingResourceSingleton.decrement()

最后在你的测试类中添加这个,让它等到countingIdlingResource减少:

init {
    IdlingRegistry.getInstance()
            .register(CountingIdlingResourceSingleton.countingIdlingResource)
}

@After
fun unregisterIdlingResource() {
    IdlingRegistry.getInstance()
            .unregister(CountingIdlingResourceSingleton.countingIdlingResource)
}

这样,检查该值是否与 flow (Jody) 返回的第一个值匹配的测试有效。

可以在github.com/jeprubio/waitflow 中找到一个工作示例,其中每 5 秒发出一个流元素,并且 espresso 测试等待直到第一个元素发出,即 CountingIdlingResourceSingleton 递减。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多