I'm working on an Android
application and I've been using Dagger
for dependency injection.
I'm trying to now test a fragment which has one of these dependencies, let's call it ProductsService
.
In my Robolectric
test I have got as far as having a test module that overrides ProductsService
:
@Module(
includes = ProductsModule.class,
injects = {
Fragment.class,
FragmentTest.class
},
overrides = true
)
static class MockProductsModule {
@Provides
@Singleton
public ProductsService providesProductsService() {
return Mockito.mock(ProductsService.class);
}
}
In my test, in order to run my fragment I construct it as follows (as seen here How can I test fragments with Robolectric?)
FragmentActivity activity = Robolectric.buildActivity(FragmentActivity.class)
.create()
.start()
.resume()
.get();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(fragment, null);
fragmentTransaction.commit();
The problem is, during this creation it makes call to Dagger
to satisfy it's dependencies:
((MyApplication)getActivity().getApplication()).inject(this);
How do I override the object graph created when the fragment is created, to use the MockProductsModule
I declare in my test?