Ivelius Ivelius - 11 months ago 69
Android Question

Android plain Junit with Dagger 2

I used to work in MVP and I usually test my presenters using a plain Junit (Not the Instrumentation !) , since Presenters only have the business logic and no references to Android internals whatsoever.

Now by switching to Dagger 2 , I understood that I have a problem setting up a "TestModule" for my app component.

  1. Creating a component will not work from within a test class (probably because "apt" is not running there)

  2. Didn't find any examples for using Dagger with a standard Junit testing. Every example I have found only relies on Instrumentation testing or Roboelectric (which basically mocks Activities and other Android related stuff) , but this is just a UI testing for me , and I don't need that.

Just to make things clear , I am talking about the tests that are located at app->src->test folder not the app->src->androidTest !

So do I do something wrong ? Or missing something ? Can anyone explain or give examples on how to use Dagger 2 in normal unit tests ?

Answer Source

I'm not sure if my solution will work for you but I see no reason it shouldn't. First I created testInjectionComponent

@Component(modules = {MockNetworkModule.class})
public interface MockInjectionComponent extends InjectionComponent {
void inject(DaggerUnitTest daggerUnitTest);

Then my Unit Tests I add injection in the before method. like so:

public void setUp() throws Exception {
    MockInjectionComponent mockInjectionComponent = DaggerMockInjectionComponent
            .mockNetworkModule(new MockNetworkModule())

Then I just Annotate my Injected Object.

EDIT : Do not forget to add testApt "com.google.dagger:dagger-compiler:$daggerVersion" at your app.gradle file .