androiddependency-injectionmockingmockitoroboguice

Roboguice and mocks: How to have roboguice inject a mock service when testing but use the REAL otherwise?


Just got my feet wet with roboguice, i like it!

I have quite a lot of methods that depend on a DB and LocationManger etc hence when i am testing these it uses the real objects, i would like to mock these objects so that when i am testing i don't have to depend on anything.

I also have been using mockito but i am unsure how i could go about this?

I know the android system comes with various mocks but i think it would be better to roll my own with mockito?

In either case i need to inject them when testing.

Anyone have any ideas on this?

Thanks in advance


Solution

  • Take a look at https://github.com/roboguice/roboguice/blob/master/astroboy/src/test/java/org/roboguice/astroboy/controller/Astroboy2Test.java which uses Modules.override() to override the default module with some test-specific configurations.

    @Before
    public void setup() {
        // Override the default RoboGuice module
        RoboGuice.setBaseApplicationInjector(Robolectric.application, RoboGuice.DEFAULT_STAGE, Modules.override(RoboGuice.newDefaultRoboModule(Robolectric.application)).with(new MyTestModule()));
        // For roboguice 4.0 and robolectric 3.1.2
        RoboGuice.getOrCreateBaseApplicationInjector(RuntimeEnvironment.application, RoboGuice.DEFAULT_STAGE, Modules.override(RoboGuice.newDefaultRoboModule(RuntimeEnvironment.application)).with(new MyTestModule()));
    }