用gradle测试一个android项目的junit测试

lig*_*igi 26 junit android junit4 gradle robolectric

我试图让测试(junit和robolectric)在Android项目中工作,但我完全陷入困境.我的主要问题是我用gradle找到的所有测试都以某种方式拉入java插件然后我得到了这个错误:

The 'java' plugin has been applied, but it is not compatible with the Android plugins.
Run Code Online (Sandbox Code Playgroud)

我目前看到的唯一出路是分成测试和应用项目 - 但我想避免这种情况.任何示例/提示都将受到高度赞赏!

官方文档中没有提到单元测试 - 只有仪器测试 - 但我希望单元测试能够快速获得结果.

new*_*our 27

你不需要Java插件,因为从目前为止我所看到的Android将主要照顾你所需要的东西.

我设法通过这个人的博客运行我的Robolectric和junit测试:http://tryge.com/2013/02/28/android-gradle-build/

我的build.gradle文件看起来像这样(我的测试文件位于{projectdir}/test目录中.

...
// Unit tests

sourceSets {
        unitTest {
                java.srcDir file('test')
                resources.srcDir file('test/resources')
        }
}

dependencies {
        unitTestCompile files("$project.buildDir/classes/debug")
        unitTestCompile 'junit:junit:4.11'
        unitTestCompile 'org.robolectric:robolectric:2.1.1'
        unitTestCompile 'com.google.android:android:4.0.1.2'
}

configurations {
        unitTestCompile.extendsFrom runtime
        unitTestRuntime.extendsFrom unitTestCompile
}

task unitTest(type:Test, dependsOn: assemble) {
        description = "run unit tests"
        testClassesDir = project.sourceSets.unitTest.output.classesDir
        classpath = project.sourceSets.unitTest.runtimeClasspath
}

build.dependsOn unitTest
Run Code Online (Sandbox Code Playgroud)

  • @Chris应该使用调试文件夹:`unitTestCompile files("$ buildDir/intermediates/classes/debug")`,但很好指出来. (3认同)

unb*_*ant 7

AndroidStudio和新的Android Gradle插件现在提供官方单元测试支持.

Android Studio 1.1+和Android Gradle插件版本1.1.0+支持此功能

现在可以将依赖关系声明为testCompile:

dependencies {
  testCompile 'junit:junit:4.12'
  testCompile "org.mockito:mockito-core:1.9.5"
}
Run Code Online (Sandbox Code Playgroud)

更多细节:单元测试支持 - Android工具项目站点.