Posted on

Android dagger override Module in test

overriding @Module classes with Dagger 2 [in tests]

ActivityTestRule, Building Instrumented Unit Tests, JUnit4 Rules with Testing Support Library, Testing Support Library, Getting Started with Testing

Example:

Main application code

public class MainApplication extends Application {

    protected MainAppComponent initComponent() {
        return DaggerMainAppComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
    }

    @Override
    public void onCreate() {
        mComponent = initComponent();
    }
}

test application code

public class TestApplication extends MainApplication {

    @Override
    protected TestAppComponent initComponent() {
        return DaggerTestAppComponent.builder()
                .applicationModule(new TestApplicationModule(this))
                .build();
    }
}

Component code

public interface TestAppComponent extends MainAppComponent {
    //code
}

Main module code

@Module
public class ApplicationModule {

    @Singleton
    @Provides
    public IFooManager provideFooManager() {
        // our code
    }
}

Test module code

public class TestApplicationModule extends ApplicationModule {

    @Override
    public IFooManager provideFooManager() {
        // our code of mock manager
    }
}

AndroidJUnitRunner

public class TestApplicationRunner extends AndroidJUnitRunner {
    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        return super.newApplication(cl, TestApplication.class.getName(), context);
    }
}

and put the runner to module build.gradle

def DAGGER_VERSION = '2.10'
dependencies {
    testApt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
    androidTestApt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
}
android {
  defaultconfig {
    // Test instrumentation configurations
        testApplicationId "com.myapp.test"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        testInstrumentationRunner "uitesting.core.runner.TestApplicationRunner"
        testHandleProfiling true
        testFunctionalTest true
  }
}

test class code

@LargeTest
@RunWith(AndroidJUnit4.class)
public class RegistrationTest {

    @Rule
    public ApplicationTestRule<TestApplication> appRule = new ApplicationTestRule<>(TestApplication.class);
    
    @Inject
    IFooManager manager;

    @Before
    public void setUp() {
        TestApplication app;
        app = (TestApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
        ((TestAppComponent)(app).getComponent()).inject(this);
    }
}
Leave a Reply

Your email address will not be published. Required fields are marked *