LoginSignup
28
27

More than 5 years have passed since last update.

Robolectric Gradle Pluginの導入手順(v.0.13.x)

Last updated at Posted at 2014-10-13

1.Robolectricとは

端末やエミュレータなしでAndroidのUnitTestを実行してくれるライブラリです。
Android SDKの標準で使えるJUnitは3.x系ですが、RobolectricではJUnit4が使えます。

本家サイト
http://robolectric.org/

ActivityやSQLiteまわりのテストをエミュレータなしで実行できるのが便利です。

2.Robolectric Gradle Pluginについて

本家がIntelliJとAndroid Studio向けにGitHubで公開しているPluginです。
https://github.com/robolectric/robolectric-gradle-plugin

テストの実行はコマンドラインからgradle経由で実行します。PluginといってもGUIからクラス単位やメソッド単位でRobolectricのテストが実行できるわけではありません。

3.設定手順

基本的にはGitHubに書いてある通りに設定すれば動作しますが自分の環境ではいくつか環境設定が必要だったため補足情報とともに設定例をまとめました。動作環境は以下の通りです。

  • Mac:OS X
  • IntelliJ:13.1.5

今回はIntelliJで動作確認しましたがAndroid Studioでも基本的に同じはずです。

3.1.Pluginをbuildscriptのdependenciesへ追加

トップレベルのbuildスクリプトを以下のように設定します。
Gradle Pluginはデフォルトで0.9を使っていましたがrobolectric-gradle-pluginを0.13に指定すると、Gradle Pluginのバージョンが低いというエラーが出たので合わせてバージョンを上げました。

${project_root}/build.gradle
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.13.+'
        classpath 'org.robolectric:robolectric-gradle-plugin:0.13.+'
    }
}

3.2 gradle-wrapper.propertiesの変更

Gradle Pluginを0.13に上げるとGradleのバージョン2.1が必要になります。 ${project_root}/gradle/wrapper/gradle-wrapper.properties を変更してGradleのバージョンを上げます。

参考:What's new in Gradle Plugin 0.13

gradle-wrapper.properties
distributionUrl=http\://services.gradle.org/distributions/gradle-2.1-all.zip

3.3 ローカルのGradleのバージョンアップ

IDE上は特にエラーになりませんが、後ほどコマンドラインからGradleを実行しますのでOS上のGradleもバージョンアップが必要です。
gradle wrapperを使う場合は以下のようにGradleのバージョンを指定します。

${project_root}/build.gradle
allprojects {
    repositories {
        mavenCentral()
    }
    task wrapper(type: Wrapper) {
        gradleVersion = '2.1'
    }
}

gradle wrapperについては以下を参照してください。

3.4 Buildスクリプトの設定

ポイントは以下

  • apply pluginにrobolectricを追加する
  • buildToolsVersionを19.1.0以上にする(Gradle Plugin 0.12以上の場合必須)
  • dependenciesにandroidTestCompileでrobolectricライブラリを追加
  • 公式の Configuration using DSL をひとまずコピペ
${module_root}/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'robolectric'  // Robolectric Plugin追加

android {
    // Gradle Pluginの実行は19.1.0以上が必須
    compileSdkVersion 19
    buildToolsVersion '19.1.0'

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    // buildでlintのエラーが出るので追加
    lintOptions {
        abortOnError false
    }
}

dependencies {
    // テストで使用する依存ライブラリ
    androidTestCompile 'org.robolectric:robolectric:2.3'
    androidTestCompile 'junit:junit:4.11'

    compile 'com.android.support:appcompat-v7:19.+'
    // コンパイルに必要な依存ライブラリ
    compile fileTree(dir: 'libs', include: ['*.jar'])

}

// とりあえずGitHubの設定例をコピペ
robolectric {
    // configure the set of classes for JUnit tests
    include '**/*Test.class'
    exclude '**/espresso/**/*.class'

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

    // 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}"
    }
}

また、後ほどコマンドラインから実行した時にlintのエラーが起きました。

Lint found errors with abortOnError=true; aborting build.

メッセージに書かれている通り abortOnError=true を設定することで解消されるようですのでBuildスクリプトに追加しています。

3.5 テストコードの配置

${module_root}/src/androidTest/java を作成し、その下にテストコードを配置します。

テストコードの書き方は今回は省略。公式がGitHubにサンプルコードを用意していますのでこれがとても参考になります。

4.実行

コマンドラインからgradleコマンドでテストを実行します。

$ gradle clean test
:example:clean                
:example:preBuild           
// 省略
Executing test for {example1Test} with result: SUCCESS      
Executing test for {example2Test} with result: SUCCESS           
Executing test for {example3Test} with result: SUCCESS      
:example:test                                          

BUILD SUCCESSFUL

Total time: 1 mins 10.625 secs

$

5.まとめ

Robolectric 2.3を使うためにGradle Pluginもバージョンを上げる必要があり、それに伴いいくつか設定が必要になります。

Robolectricは少し実行に時間がかかりますがエミュレータを起動することを考えれば時間は短いです。具体的な使い方は今回は割愛しましたがUIの自動テストを行うEspressoと併用する事例などもあるようです。

28
27
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
27