Activity test with Roboelectric 4.0

34 views
Skip to first unread message

nikhilesh singh Tak

unread,
May 22, 2020, 2:37:05 AM5/22/20
to Robolectric

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? I introduced dagger to inject mock in my test but still not able to do..

Reply all
Reply to author
Forward
0 new messages