首页 > 解决方案 > Dagger2 + Android 多模块 + 仪器测试 + 模块覆盖

问题描述

我正在将项目迁移到多模块架构中,但找不到迁移测试的方法。

为简单起见,假设有 3 个模块:

app(com.android.application)

core(com.android.library)

feature(com.android.library)

app的 gradle 包括corefeature

feature包括core


core包含Application类和一个主要的Component

// MyApplication.kt
class MyApplication : Application {
    override fun onCreate() {
        super.onCreate()
        DaggerMainComponent.create()
    }
}

// MainComponent.kt
@Component(modules = [MainModule::class])
class MainComponent {
  fun provideSomething(): Something
}

feature有它自己的Component

// FeatureComponent.kt
@Component(module = [FeatureModule::class], dependencies = [MainComponent::class])
class FeatureComponent {
    fun inject(activity: FeatureActivity)
}

// FeatureActivity.kt
class FeatureActivity : Activity {
    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        DaggerFeatureComponent.builder()
            .mainComponent(mainComponent)
            .build()
            .inject(this)
        super.onCreate(savedInstanceState)
    }
}

在迁移之前,只有 1 个组件可以在测试期间使用该runner技巧被测试模块覆盖。

我的问题是如何在测试时使用测试模块FeatureActivity?一种方法可能是FeatureComponent参与MyApplication并使用相同的策略。但理想情况下,功能组件不会暴露。我还尝试创建提供程序来提供模块,并用于PowerMock覆盖单例/最终类。

有没有优雅/标准的方法来实现这一目标?谢谢!

标签: androiddependency-injectionmockingdagger-2android-instrumentation

解决方案


您可以有一个附加testing模块(仅用于测试feature模块):

feature-testing(com.android.application)

在里面你可以有一个测试Application并提供你想要的测试模块。


推荐阅读