java - Android Studio 单元测试支持与 robolectric

标签 java android unit-testing android-studio robolectric

到目前为止,我使用 JUnit 4.x 的 robolectric 单元测试来测试我的业务逻辑。在最新版本的 Android Studio 1.1.0 中公布了 native support单元测试 junit:4.+.

我应该拒绝使用 robolectric 吗? robolectric 有一些我可能不知道的独特优势吗?

至于我用Android Studio原生测试更方便更简单。在 robolectric 中,测试结果存储在 html 文件中,可以在浏览器中显示(这对我来说不方便)。 Native Android Studio 测试结果显示在运行输出窗口中,如果某些测试失败,我们可以通过点击输出窗口中的错误轻松打开这行代码。

最佳答案

您没有理由不能同时使用两者。 Robolectric 的优势在于您可以在需要时针对实际的 Android 行为进行测试。 Plain JUnit 只会让您测试不与 Android 交互的代码部分。

这将使您能够在 Android Studio 中查看 robolectric 测试的结果以及普通的 JUnit 4.x 测试

如果您使用的是 gradle,robolectric example github repo有一个如何做的例子。

我目前正在迁移一些应用程序以使用这种方法

这里是build.gradle的相关部分

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
    }
}
dependencies {
    testCompile 'junit:junit:4.12'
    testCompile 'org.hamcrest:hamcrest-core:1.1'
    testCompile 'org.hamcrest:hamcrest-library:1.1'
    testCompile 'org.hamcrest:hamcrest-integration:1.1'
    testCompile('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'
    }
}

测试类不需要任何修改

关于java - Android Studio 单元测试支持与 robolectric,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627147/

相关文章:

java - Java 中的 Lua 语法高亮

java - 为什么 boolean 变量不显示 false 的任何结果?

Java Spring MVC 返回多个值

unit-testing - Enzyme - 如何访问和设置<input>值?

javascript - 开 Jest mock 类(class)强制不同的 react , typescript

java - 在 vscode 中启动 tomcat 时的 JVM 参数

android - Samsung Android BLE 多重读写

java - 我正在尝试访问相机

javascript - 如何根据参数调用 sinon Stub YieldsTo 函数

Android 在 travis.ci 上构建变体