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

使用Hilt WorkManager创建Baseline Profile报错的解决方案咨询

解决Hilt WorkManager配置与BaselineProfileGenerator的冲突问题

你遇到的Dagger/MissingBinding错误,核心原因是生成BaselineProfile的测试环境中,Hilt无法找到FirebaseRemoteConfigSettings的注入实例。以下是具体的解决步骤:

1. 调整BaselineProfile测试类的Hilt配置

给BaselineProfileGenerator添加Hilt测试注解和规则,确保测试流程中Hilt能正确完成依赖注入:

@OptIn(ExperimentalBaselineProfilesApi::class)
@HiltAndroidTest
class BaselineProfileGenerator {
    // Hilt规则优先级需高于BaselineProfile规则
    @get:Rule(order = 0)
    val hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val baselineProfileRule = BaselineProfileRule()

    @Before
    fun setup() {
        // 触发Hilt依赖注入初始化
        hiltRule.inject()
    }

    @Test
    fun generate() = baselineProfileRule.collectBaselineProfile(
        packageName = MY_PACKAGE
    ) {
        pressHome()
        startActivityAndWait()
    }
}

2. 提供测试环境的FirebaseRemoteConfigSettings绑定

创建测试专属的Hilt模块,为测试环境提供FirebaseRemoteConfigSettings的实例,填补Dagger的缺失绑定:

@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    // 如果你的生产依赖模块是ApplicationModule,这里替换它;无需替换则可去掉replaces参数
    replaces = [ApplicationModule::class]
)
object TestApplicationModule {
    @Provides
    fun provideFirebaseRemoteConfigSettings(): FirebaseRemoteConfigSettings {
        // 返回测试用的默认配置实例,足以满足BaselineProfile生成需求
        return FirebaseRemoteConfigSettings.Builder().build()
    }

    @Provides
    fun provideFirebaseRemoteConfig(settings: FirebaseRemoteConfigSettings): FirebaseRemoteConfig {
        val remoteConfig = FirebaseRemoteConfig.getInstance()
        remoteConfig.setConfigSettingsAsync(settings)
        return remoteConfig
    }
}

若无需替换整个生产模块,也可单独为FirebaseRemoteConfigSettings提供测试绑定:

@Module
@TestInstallIn(components = [SingletonComponent::class])
object TestFirebaseModule {
    @Provides
    fun provideFirebaseRemoteConfigSettings(): FirebaseRemoteConfigSettings {
        return FirebaseRemoteConfigSettings.Builder().build()
    }
}

3. 确认测试依赖配置

确保模块的build.gradle中包含Hilt测试所需依赖:

androidTestImplementation "com.google.dagger:hilt-android-testing:2.48"
kaptAndroidTest "com.google.dagger:hilt-compiler:2.48"

完成以上配置后,重新运行BaselineProfile生成测试,Dagger的缺失绑定错误即可解决,WorkManager的Hilt配置也能与BaselineProfileGenerator兼容运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:50:26