You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Datastore插桩测试报错kotlinx.coroutines.test.UncompletedCoroutinesError

运行DataStore插桩测试时的UncompletedCoroutinesError问题

错误信息

kotlinx.coroutines.test.UncompletedCoroutinesError: After waiting for 60000 ms, the test coroutine is not completing, there were active child jobs: [ScopeCoroutine{Active}@e24f0d2]

已尝试的解决方案

  • 使用runBlockingTest或runBlocking替代runTest
  • 通过testDispatcher调用runBlocking/runBlockingTest和runTest
  • 修改runTest的上下文
  • 在测试中启动Flow收集并在取消任务前消费数据
  • 尝试使用Flow终端操作符(如first()、take())替代turbine测试Flow

测试应用模块(TestAppModule)

@Module
@TestInstallIn(components = [SingletonComponent::class], replaces = [LocalModule::class])
object TestAppModule {

    //...

    @OptIn(ExperimentalCoroutinesApi::class)
    @Singleton
    @Provides
    fun provideFakePreferences(
        @ApplicationContext context: Context,
    ): DataStore<Preferences> {

        return PreferenceDataStoreFactory
            .create(
                scope = TestScope(),
                produceFile = {
                    context.preferencesDataStoreFile("test_pref_file")
                }
            )
    }

}

偏好仓库测试类(RepoPreferencesTest)

@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class RepoPreferencesTest {

    @get:Rule
    val hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var testDataStore: DataStore<Preferences>

    lateinit var repoPreferences: RepoPreferences

    private val testCoroutineDispatcher = UnconfinedTestDispatcher()

    private val testCoroutineScope = TestScope(testCoroutineDispatcher + Job())

    @Before
    fun setup() {
        hiltRule.inject()

        repoPreferences = RepoPreferencesImpl(testDataStore)
    }


    @Test
    fun getInitialLanguageFromInitially_ReturnsDefaultValue() = runTest {
        repoPreferences.language.test {
            assertThat(awaitItem()).isEqualTo(RemoteConstants.DEFAULT_LANGUAGE)
            cancelAndIgnoreRemainingEvents()
        }
    }

    //...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:30:57