Posted on Leave a comment

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


Main application code

public class MainApplication extends Application {

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

    public void onCreate() {
        mComponent = initComponent();

test application code

public class TestApplication extends MainApplication {

    protected TestAppComponent initComponent() {
        return DaggerTestAppComponent.builder()
                .applicationModule(new TestApplicationModule(this))

Component code

public interface TestAppComponent extends MainAppComponent {

Main module code

public class ApplicationModule {

    public IFooManager provideFooManager() {
        // our code

Test module code

public class TestApplicationModule extends ApplicationModule {

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


public class TestApplicationRunner extends AndroidJUnitRunner {
    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 "$DAGGER_VERSION"
    androidTestApt "$DAGGER_VERSION"
android {
  defaultconfig {
    // Test instrumentation configurations
        testApplicationId "com.myapp.test"
        testInstrumentationRunner ""
        testInstrumentationRunner "uitesting.core.runner.TestApplicationRunner"
        testHandleProfiling true
        testFunctionalTest true

test class code

public class RegistrationTest {

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

    public void setUp() {
        TestApplication app;
        app = (TestApplication) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext();
Leave a Reply

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.