天天看點

在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