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?
I suppose you are creating the object graph in Application.onCreate()
. If that's the case and if you're using Robolectric 2, you can create a test application as explained here and create an object graph for your tests with your test modules (prod and test application must inherit from the same base class). For more info on this, you can have a look here. Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With