【Android】Gradleでライブラリの依存関係の記述を共通化する
Android 開発において、Unit Test と Instrumented Test で使用するライブラリは、Unit Test では testImplementation
、Instrumented Test では androidTestImplementation
を使って以下のように build.gradle
を記述できます。
dependencies { // Unit Test で使用するライブラリ testImplementation "junit:junit:4.12" testImplementation "com.nhaarman:mockito-kotlin:1.5.0" testImplementation "com.squareup.okhttp3:mockwebserver:3.12.0" // Instrumented Test で使用するライブラリ androidTestImplementation "com.nhaarman:mockito-kotlin:1.5.0" androidTestImplementation "com.squareup.okhttp3:mockwebserver:3.12.0" androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test:rules:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }
この場合、mockito-kotlin
と mockwebserver
が Unit Test と Instrumented Test の両方で使用するので2回記述されています。
新たに sharedTestImplementation
という名前で Configuration を作成し、1回だけ記述するだけで Unit Test と Instrumented Test の両方で使えるようにするには以下のように記述します。
configurations { [testImplementation, androidTestImplementation]*.extendsFrom sharedTestImplementation } dependencies { // Unit Test & Instrumented Test で使用するライブラリ sharedTestImplementation "com.nhaarman:mockito-kotlin:1.5.0" sharedTestImplementation "com.squareup.okhttp3:mockwebserver:3.12.0" // Unit Test のみで使用するライブラリ testImplementation "junit:junit:4.12" // Instrumented Test のみで使用するライブラリ androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test:rules:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }
上記のほかに、例えば特定の Flavor でのみ使用したいライブラリに対しては以下のように記述できます。
android { ... productFlavors { dev {} staging {} production {} } } configurations { [devImplementation, stagingImplementation]*.extendsFrom leakCanary } dependencies { ... // dev, staging の Flavor に対して LeakCanary を使用する leakCanary "com.squareup.leakcanary:leakcanary-android:1.6.2" productionImplementation "com.squareup.leakcanary:leakcanary-android-no-op:1.6.2" }