1

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?

nik
  • 71
  • 5

1 Answers1

0

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
Alex Timonin
  • 1,872
  • 18
  • 31
  • Will it kill the purpose of DI if I have to put if else in my app code? – nik May 21 '20 at 20:01
  • No, not at all. The if else belongs to the di module code, so technically your app code has no idea what ResourceProvider implementation it gets – Alex Timonin May 22 '20 at 08:56