j2emanue
j2emanue

Reputation: 62549

DaggerMock library -how does it override module?

The DaggerMock library, is used to override dagger modules with fake implementation. Lets take a look at one robolectric topic that is confusing me:

 @RunWith(RobolectricGradleTestRunner.class) 
@Config(constants = BuildConfig.class, sdk = 21)
public class MainActivityTest { 

    @Rule public final DaggerMockRule<MyComponent> mockitoRule = new DaggerMockRule<>(MyComponent.class, new MyModule())
            .set(new DaggerMockRule.ComponentSetter<MyComponent>() { 
                @Override public void setComponent(MyComponent component) { 
                    ((App) RuntimeEnvironment.application).setComponent(component); 
                } 
            }); 

    @Mock RestService restService;

    @Mock MyPrinter myPrinter;

    @Test
    public void testCreateActivity() { 
        when(restService.doSomething()).thenReturn("abc");

        Robolectric.setupActivity(MainActivity.class); 

        verify(myPrinter).print("ABC");
    } 
} 

So i want to know, with this Rule what exactly is happening ? I can see that RestService was being provided by MyModule but is now being replaced with a mock. But in the examples i don't see a @Inject anywhere so i'm confused how the module was even used in the first place to provide any dependencies ?

Upvotes: 3

Views: 703

Answers (1)

Fabio Collini
Fabio Collini

Reputation: 474

I am the author of DaggerMock, thanks for trying it!

The implementation is a bit complicated, the rule create a dynamic subclass of the module (using mockito) and override the provides methods. The rule scans the test fields so it return a field when the module has a method that returns the same type.

The final result is very similar to Mockito InjectMocks annotation. You can take a look at the implementation on github, the core class that override the module is this: https://github.com/fabioCollini/DaggerMock/blob/master/lib/src/main/java/it/cosenonjaviste/daggermock/MockOverrider.java

I release this lib just a week ago, any feedback is welcome!

Upvotes: 5

Related Questions