【发布时间】:2018-04-18 09:44:52
【问题描述】:
如果我们只使用普通的匕首 2。在 application 类中,我们将拥有一个包含 AppComponent 的属性。然后我们可以在 espresso 测试期间交换它。
但是当我使用dagger-android 2.15 设置我的项目时。如果使用过多的匕首魔法,事情就会变得更加隐晦。代码更干净,但测试有点困难。
这是application 类:
class App : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent
.builder()
.create(this)
.build()
}
}
这是 HomeActivity
class HomeActivity : DaggerAppCompatActivity() {
@Inject
lateinit var userPreference: UserPreference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
if (!this.userPreference.memberRegistered) {
goToActivity(EntryActivity::class.java)
}
}
}
以这段代码为例。如何模拟注入的userPreference.memberRegistered 可能是下面的 HTTP 调用?
【问题讨论】:
-
其实我昨天刚刚写了一篇关于这个的博文:dev.to/autonomousapps/…
-
@AutonomousApps 阅读!谢谢!真的很棒的教程!似乎只需要用接口替换 DaggerApplication。
标签: android kotlin mocking android-espresso dagger