Search code examples
androidautomated-testssingletondagger-2android-instrumentation

instantiate a singleton class in instrumentation test makes another instance instead of using previous one


I'm working on instrumented test in android, I use Dagger to make a singleton instance from a class called PlugAndPlayInterceptor. this class helps me to set different interceptors based on test needs. I inject it in my test class, when I set the interceptor it is good, but when I need to call interceptor it is null because somewhere else it makes another instance and uses the new one. I made a sample project based on and put it here. please check it, I will appreciate if someone helps me to solve this issue.


Solution

  • What you are doing is technically creating the component twice. You should omit the one in SharedTabletSetup.

    For that, you need to do some changes. First, make TestAppComponent accessible from TestApp:

    class TestApp : MyApp() {
        lateinit var component: TestAppComponent
    
        override fun initDagger() {
            component = DaggerTestAppComponent.builder()
                .application(this)
                .build()
    
            component.inject(this)
        }
    }
    

    The last change would be to use the existing component to do the inject. So open SharedTabletSetup.kt and remove the following lines:

    val appInjector = DaggerTestAppComponent.builder()
                .application(app)
                .build()
    appInjector.inject(this)
    

    Now instead, inject the dependencies using the main component:

    (app as TestApp).component.inject(this)