9

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?

Community
  • 1
  • 1
m00sey
  • 689
  • 6
  • 6

1 Answers1

12

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.

futtetennista
  • 1,876
  • 1
  • 20
  • 33
  • Nice suggestion. I made a method to inject graph object and used that in tests but your solution doesn't have drawbacks of smell design (but have drawbacks of smell tests :)). Thank you! – Eugen Martynov Jun 24 '13 at 04:46