Dagger用于Robolectric测试

时间:2014-08-13 18:24:14

标签: android robolectric dagger

我想在我的robolectric测试中使用Dagger注射,但我在设置时遇到了麻烦。我的代码示例中的错误在哪里。我怎样才能做到这一点?

我的主要模块

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

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

我的测试模块

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

}

我的制作主要课程

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

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

我的robolectric测试应用程序类

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);
    }

错误:

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.

当我将我的robolectric应用程序类方法更改为:

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

结果:

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.

更新

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"

1 个答案:

答案 0 :(得分:0)

您应该提供TestModule并且您正确地执行此操作(TestModule必须位于从getModules返回的模块列表中)。您可以在此处找到第二个错误的解决方案:Dagger example built through eclipse fails with 'Please ensure that code generation was run for this module.'