【发布时间】:2017-03-14 18:10:39
【问题描述】:
我希望这只是我在这里做错了。我正在尝试使用 Dagger 2.0 为我的 JUnit 测试注入依赖项(不是 Espresso 测试,只是纯 JUnit)。所以,我有一个“主”java 模块和一个“测试”java 模块。在主模块中,我有一个 Dagger 模块和一个组件:
@Module
public class MainModule {
@Provides
public Widget provideWidget() {
return new ConcreteWidget();
}
}
...
@Component (modules = MainModule.class)
public interface MainComponent {
void inject(WidgetConsumer consumer);
}
在我的测试模块中,我有以下内容:
@Module
public class TestModule {
@Provides public Widget provideWidget() {
return new Widget() {
@Override
public void doThing() {
int y = 6;
y ++;
}
};
}
}
...
@Component(modules = TestModule.class)
public interface TestComponent extends MainComponent{
}
我的 build.gradle 具有如下所示的依赖项:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.2.0'
testCompile 'junit:junit:4.12'
compile 'com.google.dagger:dagger:2.9'
testCompile 'com.google.dagger:dagger:2.9'
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
testAnnotationProcessor 'com.google.dagger:dagger-compiler:2.9'
}
无论出于何种原因,Dagger 生成 DaggerMainComponent,但拒绝生成 DaggerTestComponent。构建时,gradle 输出中似乎没有错误。
事情是这样的...我认为注释处理器正在运行,但不知何故,android gradle 插件无法在编译时提取那些生成的源。我检查了 app/build/generated/source/apt/test/ 目录并在其中找到了DaggerTestComponent.java,但由于某种原因,它没有作为依赖项导入。
【问题讨论】:
-
如果可能,请发布一个测试项目。
-
当然可以。编辑了我的回复以添加指向测试项目的链接。
标签: java android junit android-gradle-plugin dagger-2