You need to enable JavaScript to run this app. Espresso测试中如何正确等待协程响应以替代固定延迟
优惠活动
大模型
产品
解决方案
定价
更多

Espresso测试中如何正确等待协程响应以替代固定延迟

协程调度导致Espresso测试不稳定问题

该函数在Activity中执行,用于检查特定Feature Flag是否启用,项目中注入了dispatcher.io(),因此测试模式下调度器为Main。

fun isFeatureFlagEnabled(nameKey: String, completion: (enabled: Boolean) -> Unit) {
    CoroutineScope(context = dispatcher.io()).launch {
        val featureFlag = featureFlagsRepository.featureFlagsDao.getFeatureFlag(nameKey)
        if (featureFlag != null) {
            completion(featureFlag.isEnabled)
        }
        else {
            completion(false)
        }
    }
}

Activity中的调用逻辑

private fun launchClearentCardOnFileBaseOnFeatureFlag(cardNavHelper: CardNavHelper){
    featureFlagsHelper?.isFeatureFlagEnabled(CLEARENT_CARD_ON_FILE){enable ->
        if(enable){
            putFragment(
                ClearentNativeFormFragment.newInstance(cardNavHelper))
        }else{
            putFragment(
                ClearentCardOnFileFormFragment.newInstance(cardNavHelper))
        }
    }
}

测试失败原因

Espresso不会等待传入作为参数的lambda函数完成数据库(为inMemoryDatabase)查询并返回响应,因此测试运行直接失败。
当前可临时跑通的测试用例:

@Test
fun testFFClearentNativeFormEnable(){
    mockWebServer.setDispatcher(BusinessWithAddonsAndPaymentProcessorClearentDispatcher())
    val application = ApplicationProvider.getApplicationContext<SchedulicityApplication>()
    runBlocking(Dispatchers.Main) {
        application.featureFlagsHelper.featureFlagsRepository.featureFlagsDao.insertFeatureFlags(
            featureFlagsEnable
        )
    }
    intent.putExtra(Constants.INTENT_KEY_CARD_ON_FILE_EXTRAS, cardNavHelperFromClientRecord)
    activityTestRule.launchActivity(intent)
    
    runBlocking { delay(10000) }
    populateClearentForm(validCardNumber = false, validExpDate = true)
}

待解决的问题

目前只能通过添加*runBlocking { delay(10000) }*这段延迟代码让测试通过,否则就会运行失败。需要找到可以在UI线程中等待协程响应的方法,让测试用例可以稳定执行。

内容的提问来源于stack exchange,提问作者Oscar Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.23 03:54:05