在仪器测试中实例化一个单例 class 创建另一个实例而不是使用前一个实例
instantiate a singleton class in instrumentation test makes another instance instead of using previous one
我正在 android 中进行仪器测试,我使用 Dagger 从 class 中创建一个名为 PlugAndPlayInterceptor 的单例实例。这个 class 帮助我根据测试需要设置不同的拦截器。我在我的测试中注入它 class,当我设置拦截器时它很好,但是当我需要调用拦截器时它是空的,因为它在其他地方创建了另一个实例并使用了新实例。我做了一个基于 here 的示例项目。请检查一下,如果有人帮助我解决这个问题,我将不胜感激。
您所做的是在技术上两次创建组件。您应该省略 SharedTabletSetup
.
中的那个
为此,您需要进行一些更改。首先,使 TestAppComponent
可从 TestApp
:
访问
class TestApp : MyApp() {
lateinit var component: TestAppComponent
override fun initDagger() {
component = DaggerTestAppComponent.builder()
.application(this)
.build()
component.inject(this)
}
}
最后的更改是使用现有组件来执行 inject
。所以打开 SharedTabletSetup.kt
并删除以下行:
val appInjector = DaggerTestAppComponent.builder()
.application(app)
.build()
appInjector.inject(this)
现在改为使用主要组件注入依赖项:
(app as TestApp).component.inject(this)
我正在 android 中进行仪器测试,我使用 Dagger 从 class 中创建一个名为 PlugAndPlayInterceptor 的单例实例。这个 class 帮助我根据测试需要设置不同的拦截器。我在我的测试中注入它 class,当我设置拦截器时它很好,但是当我需要调用拦截器时它是空的,因为它在其他地方创建了另一个实例并使用了新实例。我做了一个基于 here 的示例项目。请检查一下,如果有人帮助我解决这个问题,我将不胜感激。
您所做的是在技术上两次创建组件。您应该省略 SharedTabletSetup
.
为此,您需要进行一些更改。首先,使 TestAppComponent
可从 TestApp
:
class TestApp : MyApp() {
lateinit var component: TestAppComponent
override fun initDagger() {
component = DaggerTestAppComponent.builder()
.application(this)
.build()
component.inject(this)
}
}
最后的更改是使用现有组件来执行 inject
。所以打开 SharedTabletSetup.kt
并删除以下行:
val appInjector = DaggerTestAppComponent.builder()
.application(app)
.build()
appInjector.inject(this)
现在改为使用主要组件注入依赖项:
(app as TestApp).component.inject(this)