9
9

More than 5 years have passed since last update.

Retrolambda+RobolectricでUnitTestするときのメモ

Posted at

Androidアプリ開発でラムダ式使いたいよね

インデント量が減らせるし、慣れれば可読性が保てるので導入したいよね。

Retrolambdaを導入してみた

JDK1.8入れて、Pluginを導入するだけなので簡単に導入できる。

// build.gradle
buildscript {
    dependencies {
        classpath 'me.tatarka:gradle-retrolambda:3.2.5' // support Lambda
    }
}

apply plugin: 'me.tatarka.retrolambda' /* Android Lambda Support */

assembleはできたけどUnitTestビルドが行えない

ビルドしようとしたらいつものエラーが出てビルドできない


Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
:app:compileGoogleplayDebugUnitTestJavaWithJavac
javacTask: ターゲット・リリース1.7がデフォルトのソース・リリース1.8と競合しています
Error:Execution failed for task ':app:compileGoogleplayDebugUnitTestJavaWithJavac'.


Compilation failed; see the compiler error output for details.

ネットの海を探したがダメだった

八木さんの情報をbuild.gradleを修正したけど、やっぱりビルドできない。

tasks.withType(Test) {
    project.tasks
            .findAll {
        task -> (task.name ==~ /compile.*?TestJava/)
    }
    .each { task ->
        task.doFirst {
            def buildPath = "$project.buildDir/retrolambda"
            def jarPath = "$buildPath/$project.android.compileSdkVersion"
            def javac = "${project.retrolambda.tryGetJdk()}/bin/javac"

            sourceCompatibility = JavaVersion.VERSION_1_8
            targetCompatibility = JavaVersion.VERSION_1_8

            options.fork = true
            options.compilerArgs += ["-bootclasspath", "$jarPath/android.jar"]
            options.forkOptions.executable = javac
        }
    }
}

ちょっとイジッて解決した

タスク名をよく見たら${compile}${flavor名}DebugUnitTestJava"WithJavac"というタスク名になっていた。タスク名が微妙に変わっていたので、それに追従して正規表現パターンとやることをちょっと変えた。

これで無事にUnitTestが通るようになった。

tasks.withType(Test) {
    project.tasks
            .findAll {
        task -> (task.name ==~ /compile.*?TestJava.*?/)
    }
    .each { task ->
        task.doFirst {
            sourceCompatibility = JavaVersion.VERSION_1_8
            targetCompatibility = JavaVersion.VERSION_1_8
        }
    }
}

最後に

きっとこの情報は1年以内に使えなくなるんだろうな・・・(AS2.0を眺めながら)

9
9
0

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
9
9