Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Dagger Module in Robolectric Tests

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?

like image 490
m00sey Avatar asked Jun 20 '13 13:06

m00sey


1 Answers

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.

like image 197
futtetennista Avatar answered Nov 08 '22 01:11

futtetennista