简体   繁体   中英

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:

app (com.android.application)

core (com.android.library)

feature (com.android.library)

app 's gradle includes core and feature

feature includes core


core contains the Application class, and a main 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

// 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.

My problem is how to use test modules while testing FeatureActivity ? One way could be to have the FeatureComponent in MyApplication and use the same tactic. 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.

Is there any elegant/standard way to achieve this? Thanks!

You can have an additional testing module (just for testing the feature module):

feature-testing (com.android.application)

Inside you can have a testing Application and supply testing modules however you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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