android - 使用 Robolectric 测试将设备上的仪器化测试添加到项目中

标签 android gradle robolectric robolectric-gradle-plugin

我有一个使用 Robolectric 进行测试的 Android 项目。 build.gradle 的相关部分看起来有点像这样:

apply plugin: 'robolectric'

robolectric {
    include '**/*Test.class'
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile 'org.hamcrest:hamcrest-integration:1.1'
    androidTestCompile 'org.hamcrest:hamcrest-core:1.1'
    androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
    androidTestCompile('junit:junit:4.12') {
        exclude module: 'hamcrest-core'
    }
    androidTestCompile('org.robolectric:robolectric:2.4') {
        exclude module: 'classworlds'
        exclude module: 'commons-logging'
        exclude module: 'httpclient'
        exclude module: 'maven-artifact'
        exclude module: 'maven-artifact-manager'
        exclude module: 'maven-error-diagnostics'
        exclude module: 'maven-model'
        exclude module: 'maven-project'
        exclude module: 'maven-settings'
        exclude module: 'plexus-container-default'
        exclude module: 'plexus-interpolation'
        exclude module: 'plexus-utils'
        exclude module: 'wagon-file'
        exclude module: 'wagon-http-lightweight'
        exclude module: 'wagon-provider-api'
    }
    androidTestCompile 'com.android.support:support-v4:21.0.3'
}

所有 Robolectric 测试都在 src/androidTest/java/my/package/*Test.java 中。这一切都运作良好。我可以将测试作为普通 Gradle 构建的一部分运行,也可以通过 IntelliJ 的 JUnit GUI 运行。

现在我需要添加一些不能使用 Robolectric 并且需要在真实 Android 设备上运行的测试。鉴于我已经不得不为我的 Robolectric 测试使用 androidTest 变体,我如何才能将我的插桩测试添加到该项目,并且仍然允许 Robolectric 测试在没有设备的情况下运行?

最佳答案

这是 super 过时的设置,我建议:

  1. 使用最新稳定的 android gradle 插件:

    buildscript {
      dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
      }
    }
    
  2. 删除 Robolectric gradle 插件:

    //apply plugin: 'robolectric'
    
    //robolectric {
    //    include '**/*Test.class'
    //}
    
  3. 将测试源移动到 test文件夹

  4. 更改 androidTestCompiletestCompile

现在您可以使用 ./gradlew test<Flavour>DebugUnitTest 运行测试.您可以将仪器测试添加到 androidTest文件夹。

同时考虑将 Robolectric 升级到 3.1版本

关于android - 使用 Robolectric 测试将设备上的仪器化测试添加到项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37859637/

相关文章:

android - ObjectAnimator.setDuration 被忽略

android - 在使用 Robolectric 测试 Android 应用程序时,如何创建影子类来解决与自定义属性相关的崩溃问题?

android - Robolectric 2.x + Jenkins 上的 Maven 因 APKLIB 依赖项而失败

camera - camera.takePicture 后不显示图像审查

java - 想要创建一个通用的 AsyncTask - 如何?

javascript - 如何将整个javascript函数注入(inject)webview并从android调用它

groovy - 从 Gradle 运行 Groovy 脚本

android - Gradle 1.8 卡在 Resolving dependencies for Android 但 1.6 get fine

java - 在java 8中的gradle中的jar的Manifest文件中添加Classpath

android - 从 gradle 运行单个 Android(单元)测试而不加载其他项目依赖项