【发布时间】:2016-03-26 03:57:12
【问题描述】:
我在这里遵循指南:https://github.com/ecgreb/dagger-2-testing-demo
我的 app/src/main 中有以下设置(省略了注入和 @Provides 代码):
public class FlingyApplication extends Application {
@Singleton
@Component(modules = { FlingyModule.class })
public interface FlingyComponent
}
@Module
public class FlingyModule
在 app/src/test 中:
public class TestFlingyApplication extends Application {
@Singleton
@Component(modules = { TestFlingyModule.class })
public interface TestFlingyComponent extends FlingyComponent
}
@Module
public class TestFlingyModule
到目前为止,它几乎与示例 github 相同。当 dagger 去为 src/main 中的组件构建器生成代码时,它们会正确生成。但是,Dagger 不会为 src/test 中的组件构建器生成代码。
我的主要 build.gradle:
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-alpha3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.5.1'
}
我的应用程序/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
android {
# There is obviously more in here, but this is the custom part:
packagingOptions {
exclude 'META-INF/services/javax.annotation.processing.Processor'
}
}
dependencies {
compile 'com.squareup:otto:1.3.8'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.google.dagger:dagger:2.0.1'
apt 'com.google.dagger:dagger-compiler:2.0.1'
compile 'javax.annotation:javax.annotation-api:1.2'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'
testCompile 'com.neenbedankt.gradle.plugins:android-apt:1.4'
testCompile 'junit:junit:4.12'
testCompile 'org.robolectric:robolectric:3.0'
testCompile 'org.mockito:mockito-core:1.10.19'
}
所以当我构建时,我得到了DaggerFlingyApplication_FlingyComponent 类,但没有得到DaggerTestFlingyApplication_TestFlingyComponent
我注意到的一件有趣的事情是,如果我换行:
apt 'com.google.dagger:dagger-compiler:2.0.1'
# TO
compile 'com.google.dagger:dagger-compiler:2.0.1'
我在运行./gradlew compileDebugUnitTestSources 时看到以下内容:
:app:compileDebugJavaWithJavac
Note: /app/build/generated/source/apt/debug/com/jy/flingy/DaggerFlingyApplication_FlingyComponent.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:app:preDebugUnitTestBuild UP-TO-DATE
:app:prepareDebugUnitTestDependencies
:app:compileDebugUnitTestJavaWithJavac
Note: /app/build/intermediates/classes/test/debug/com/jy/flingy/DaggerTestFlingyApplication_TestFlingyComponent.java uses unchecked or unsafe operations.
我不知道为什么它会构建为中间体,我假设我需要 build.gradle 文件来使用 apt 而不是 compile,但我似乎无法弄清楚如何让它工作.我知道这绝对有可能。
【问题讨论】:
-
本文档 (google.github.io/dagger/testing.html) 建议不要使用 dagger 进行单元测试..
-
如果您有很多依赖项,那么它可能指向您的单元测试测试多个单元。也就是说,谷歌并不总是最了解(喘气!),这是他们的一个相当广泛的声明。在特定情况下在单元测试中使用匕首对我们来说效果很好,因此这个问题。