在Android Studio中用Gradle添加Robolectric

我们用Robolectric测试的话需要在gradle中进行配置,国内的详细教程太过简易,而且很多是低版本下的配置方案。所以经过本人的仔细摸索,找到了现在高版本中的配置方案,主要还是参考了官网的配置教程:https://github.com/robolectric/robolectric-gradle-plugin

下面贴上完整的步骤,看完后就能配置成功了~

下面红字部分就是要添加的部分。

首先,在最外面的build.gradle中配置classpath

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.0'
        classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

然后在,项目的build.gradle中进行如下配置:

apply plugin: 'com.android.application'
// 1.test plugin
apply plugin: 'org.robolectric'
android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "kale.testapplication"
        minSdkVersion 15
        targetSdkVersion 18
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'LICENSE.txt'
    }
}

dependencies {
    androidTestCompile 'junit:junit:4.12'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    // 2. test-libs
    androidTestCompile 'org.robolectric:robolectric:2.4'
}

// 3. test settings
robolectric {
    // Configure includes / excludes
    include '**/*Test.class'
    exclude '**/espresso/**/*.class'

    // Configure max heap size of the test JVM
    maxHeapSize = '2048m'

    // Configure the test JVM arguments - Does not apply to Java 8
    jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier'

    // Specify max number of processes (default is 1)
    maxParallelForks = 4

    // Specify max number of test classes to execute in a test process
    // before restarting the process (default is unlimited)
    forkEvery = 150

    // configure whether failing tests should fail the build
    ignoreFailures true

    // use afterTest to listen to the test execution results
    afterTest { descriptor, result ->
        println "Executing test for ${descriptor.name} with result: ${result.resultType}"
    }
}

参考自:

http://blog.yohei.org/android-studio-gradle-robolectric1/

https://github.com/robolectric/robolectric-gradle-plugin

原文地址:https://www.cnblogs.com/tianzhijiexian/p/4484025.html