android - 如何在 Android Studio 中设置 robolectric

标签 android android-studio robolectric android-gradle-plugin

我正在使用单元框架 robolectric 测试我的 android 应用程序。我已经安装了 Android Studio (.4.6)

所有博客都说“为了能够使用 Gradle 运行 Android 单元测试,我们需要将 Gradle Android Test plug-in 添加到构建脚本中。”

但是现在已经弃用了,那么我如何在不使用它的情况下设置它,或者我必须使用它。

最佳答案

我正在使用 com.github.jcandksolutions.gradle:android-unit-test:+

因此在您的根目录 build.gradle(buildscript 部分)中:

repositories {
    mavenLocal()
    mavenCentral()
    maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
dependencies {
    classpath 'com.android.tools.build:gradle:0.8.+'
    classpath 'com.github.jcandksolutions.gradle:android-unit-test:+'
}

在您应用的 build.gradle 中

apply plugin: 'android'

android {

    [...]

    sourceSets {
        // this sets the root test folder to src/test overriding the default src/instrumentTest
        instrumentTest.setRoot('src/test')
    }
}

apply plugin: 'android-unit-test'

dependencies {
    // example dependencies
    instrumentTestCompile 'junit:junit:4.+'
    instrumentTestCompile 'org.robolectric:robolectric:2.3-SNAPSHOT'
    testCompile 'junit:junit:4.+'
    testCompile 'org.robolectric:robolectric:2.3-SNAPSHOT'
}

请注意,您必须声明依赖关系两次(一次用于 instrumentTestCompile 范围,一次用于 testCompile 范围(用于 android-unit-test 插件))。这至少对于这个版本的 Android Studio 和插件是必要的。

然后您可以从终端使用 gradlew test 运行测试(在 Android Studio 中或独立的)。

旁注 1:我在 Windows 上使用 Android Studio 终端集成时遇到了一些问题。它不能很好地处理有限的可用水平空间,截断输出。结果我开始使用 ConEmu ,避免使用 Android Studio 中的嵌入式终端和标准的 cmd.exe。

关于android - 如何在 Android Studio 中设置 robolectric,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22298821/

相关文章:

android - react native fbsdk 问题 - 任务 :react-native-fbsdk:compileDebugJavaWithJavac FAILED

android-layout - 此 View 不受垂直方向限制。在运行时它会跳到左边,除非你添加垂直约束

java - 当数据大小增加超过 5100 个字符时,Android WebView 不显示

android - Glide : onError Callback

android - Systrace 输出错误

android - 在 Android 项目中使用 Espresso 2.0 + Roboelectric

android - 带有 map 自定义 fragment 的 Robolectric 3.0 InflateException

java - 创建 FragmentTabHost 导致一些麻烦

Android Studio 安装后无法启动

android - Robolectric - 包 targetSdkVersion=30 > maxSdkVersion=29