android编译异常'prepareDebugAndroidTestDependencies'

Error:Execution failed for task ‘:app:prepareDebugAndroidTestDependencies’.

今天在测试Dagger2时遇到异常,运行是能够通过的,但是build时出现下面异常

1
Error:Execution failed for task ':app:prepareDebugAndroidTestDependencies'.

ASyichang

最后在stackoverflow上找到答案。

在app的build.gradle的android { }中添加如下代码即可:

configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
}

具体原因是因为:

When instrumentation tests are run, both the main APK and test APK share the same classpath. Gradle build 

will fail if the main APK and the test APK use the same library (e.g. Guava) but in different versions. If 

gradle didn't catch that, your app could behave differently during tests and during normal run (including 

crashing in one of the cases).

To make the build succeed, just make sure both APKs use the same version. If the error is about an indirect 

dependency (a library you didn't mention in your build.gradle), just add a dependency for the newer version 

to the configuration ("compile" or "androidTestCompile") that needs it. You can also use Gradle's resolution 

strategy mechanism. You can inspect the dependency tree by running ./gradlew :app:dependencies and ./gradlew 

:app:androidDependencies.

大致意思就是:

当运行测试时,主APK和测试APK共享类的路径,当主APK和测试APK使用相同的库但是是不同版本时就会出现这样的错误。

另外的解决办法

除了上面的方案,还有另外一种解决方案,同样来源于stackoverflow

androidTestCompile替换为androidTestCompile 'com.android.support:support-annotations:xx.xx.x'其中xx.xx.x和项目引入的com.android.support:appcompat-v7:xx.xx.x相同即可。

不过此方法在编译后会引起androidTest包下的测试文件异常,不用的删除即可。