Dagger2 + ActivityInjection + AndroidXTest/Espresso/RoboElectric in library project

106 Views Asked by At

I am working on android library module and I want to test the standalone activity in my module. I was following the article https://medium.com/androiddevelopers/write-once-run-everywhere-tests-on-android-88adb2ba20c5 to use roboelectric and androidx test with espresso. I recently introduced dagger 2 to my library project.

With that my Activity looks like this:

class XYZLibBaseActivity : AppCompatActivity(){

    @Inject
    lateinit var resourceProvider: ResourceProvider

    override fun onCreate(savedInstanceState: Bundle?) {
        //creating the dagger component
        DaggerXYZLibComponent.factory().create(application).inject(this)

        super.onCreate(savedInstanceState)
    }
}

My component declaration is 

@Component(modules = [ResourceProviderModule::class])
interface XYZLibComponent{

    @Component.Factory
    interface Factory{
        fun create(@BindsInstance application: Application):XYZLibComponent
    }

    fun inject(xyzLibBaseActivity: XYZLibBaseActivity)
}

and dagger module is 

@Module
class ResourceProviderModule {

    @Provides
    fun provideResourceProvider(application: Application): ResourceProvider{
        return ResourceProviderImpl(application.applicationContext)
    }

}

This works perfectly fine and I don't want the underlying application to use dagger 2.

Now I wan to test my activity without depending on the underlying application or application class. How can I inject mock ResourceProvider in the activity?

1

There are 1 best solutions below

2
On

One of many options is

  1. create 2 flavors in your gradle config: real and mock
  2. in both flavors, define a boolean buildConfigField flag
  3. In your provideResourceProvider, return a corresponding implementation based on the flag's value