[英]Dagger2 + Android multi module + instrumentation test + module override
I'm migrating a project into a multi module architecture, but can't find a way to migrate the tests. 我正在将项目迁移到多模块体系结构中,但是找不到迁移测试的方法。
To keep it simple, let's say there are 3 modules: 为了简单起见,假设有3个模块:
app
(com.android.application) app
(com.android.application)
core
(com.android.library) core
(com.android.library)
feature
(com.android.library) feature
(com.android.library)
app
's gradle includes core
and feature
app
的gradle包括core
和feature
feature
includes core
feature
包括core
core
contains the Application
class, and a main Component
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
has its own Component
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)
}
}
Prior to the migration, there was only 1 component that could be overridden with test modules, during the test, using the runner
trick. 迁移之前,在测试过程中,仅可以使用runner
技巧将1个组件替换为测试模块。
My problem is how to use test modules while testing FeatureActivity
? 我的问题是在测试FeatureActivity
如何使用测试模块? One way could be to have the FeatureComponent
in MyApplication
and use the same tactic. 一种方法是在MyApplication
使用FeatureComponent
并使用相同的策略。 But ideally, feature components are not exposed. 但理想情况下,特征组件不公开。 I've also tried to create providers to supply modules, and use PowerMock
to override singleton/final classes. 我还尝试创建提供程序以提供模块,并使用PowerMock
覆盖单例/最终类。
Is there any elegant/standard way to achieve this? 是否有任何优雅/标准的方法来实现这一目标? Thanks! 谢谢!
You can have an additional testing
module (just for testing the feature
module): 您可以具有其他testing
模块(仅用于测试feature
模块):
feature-testing
(com.android.application) feature-testing
(com.android.application)
Inside you can have a testing Application
and supply testing modules however you want. 内部可以有一个测试Application
并根据需要提供测试模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.