0

I want to use Dagger injections in my robolectric tests but I have trouble with set it up. Where is error in my code sample. How can I make this work?

My main module

@Module(
        includes = DatabaseModule.class,
        injects = {
                MainActivity.class,
        }
)
public class MainModule {
    private final MyApplication application;

    public MainModule(MyApplication application) {
        this.application = application;
    }

My test module

@Module(
        overrides = true,
        includes = MainModule.class,
        injects = {
                TestMyApplication.class,
                MyApplication.class
        }
)
public class TestModule {

}

My production main class

public class MyApplication extends Application {
    @Inject
    public MyApplication() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        graph = ObjectGraph.create(getModules().toArray());
        inject(this);
    }
    ...
}

My robolectric test application class

public class TestMyApplication extends MyApplication {

    @Override
    protected List<Object> getModules() {
        List<Object> modules = super.getModules();
        return modules;
    }

    public void injectMocks(Object object) {
        ((TestMyApplication) Robolectric.application).inject(object);
    }

Error:

java.lang.RuntimeException: java.lang.IllegalArgumentException: No inject registered for members/info.korzeniowski.MyApplication.TestMyApplication. You must explicitly add it to the 'injects' option in one of your modules.

When I change in My robolectric application class method to this:

@Override
protected List<Object> getModules() {
    List<Object> modules = super.getModules();
    modules.add(new TestModule());
    return modules;
}

Result:

java.lang.RuntimeException: java.lang.IllegalStateException: Module adapter for class info.korzeniowski.walletplus.test.TestModule could not be loaded. Please ensure that code generation was run for this module.

Update

gradle.build:

compile 'com.jakewharton:butterknife:5.1.2'
def daggerVersion = '1.2.+'
apt "com.squareup.dagger:dagger-compiler:$daggerVersion"
compile "com.squareup.dagger:dagger:$daggerVersion"
compile "com.squareup:javawriter:2.2.1"
Community
  • 1
  • 1
WojciechKo
  • 1,511
  • 18
  • 35

1 Answers1

0

You should provide the TestModule and you are doing it right (TestModule must be in the list of modules returned from getModules). You can find solution for the second error here: Dagger example built through eclipse fails with 'Please ensure that code generation was run for this module.'

tomrozb
  • 25,773
  • 31
  • 101
  • 122
  • Not working. I've updated my question and added gradle.build fragment. Is that correct? I use Android Studio. – WojciechKo Aug 13 '14 at 21:57