简体   繁体   English

Dagger2 + Android多模块+仪表测试+模块覆盖

[英]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包括corefeature

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM