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

时间:2019-07-07 00:15:04

标签: android dependency-injection mocking dagger-2 android-instrumentation

我正在将项目迁移到多模块体系结构,但是找不到迁移测试的方法。

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

app(com.android.application)

core(com.android.library)

feature(com.android.library)

app的摇篮包括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)
    }
}

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

我的问题是在测试FeatureActivity时如何使用测试模块?一种方法是在FeatureComponent中使用MyApplication并使用相同的策略。但理想情况下,特征组件不公开。我还尝试创建提供程序以提供模块,并使用PowerMock覆盖单例/最终类。

是否有任何优雅/标准的方法来实现这一目标?谢谢!

1 个答案:

答案 0 :(得分:0)

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

feature-testing(com.android.application)

内部,您可以拥有测试Application并根据需要提供测试模块。