Android Studioで自動テストを行いたいエンジニア向けの記事です。
Android JUnitでUIテストを楽に実装できるライブラリ、EspressoをAndroid Studioで使用する方法です。
上記のAndroid Developers公式アカウントで、Espresso2.0のリリースが発表されました。重要なのは、Android Supportライブラリにコントリビュートされたことです。Android SDK ManagerでAndroid Supportライブラリをダウンロードしておけば、いつでもEspressoが使用できます。
セットアップ
Android SDK ManagerでAndroid Supportライブラリを最新バージョンに更新してください。
app/build.gradleを次のように変更します。
- Espressoライブラリの追加
- testInstrumentationRunnerの指定
- エラー対策
Android Testで使用するため、dependenciesにandroidTestCompile指定でEspressoライブラリの追加をします。
1 2 3 4 5 6 7 |
dependencies { // for AndroidTest compile 'com.android.support:support-annotations:21.0.3' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0' androidTestCompile 'com.android.support.test:testing-support-lib:0.1' } |
Android TestのRunnerを次のように指定します。
1 2 3 4 5 |
android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } } |
Build実行時にエラーが発生するので、次のように’LICENSE.txt’をexculeします。
1 2 3 4 5 |
android { packagingOptions { exclude 'LICENSE.txt' } } |
これらの指定で簡単にEspressoが使用できるようになります。
JUnitのサンプルコード
次はActivityInstrumentationTestCase2を継承したJUnitのサンプルコードです。
ポイントは以下の項目です。
- クラス宣言に@RunWith(AndroidJUnit4.class)アノテーションを追加。
- setUpメソッドをpublicに変更、@Beforeアノテーションを追加
- setUpメソッドにて、injectInstrumentationメソッドをコール
- tearDownメソッドをpublicに変更、@Afterアノテーションを追加
- 各テストメソッドに@Testアノテーションを追加
各テストメソッドは”testXXXX”にする必要があります。
“testXXXX”で無い場合、./gradlew connectedAndroidTestを実行してもテストされないので注意しましょう。
(Android Studio 1.1+Android Support Library21.0.3の環境で確認)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
@RunWith(AndroidJUnit4.class) public class SampleFragmentActivityTest extends ActivityInstrumentationTestCase2<SampleFragmentActivity> { public SampleFragmentActivityTest() { super(SampleFragmentActivity.class); } @Before public void setUp() throws Exception { super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); } @After public void tearDown() throws Exception { super.tearDown(); } @Test public void testHomeKey() { } } |
著者プロフィール
- クックビズ開発部 孤高のAndroider
最近書いた記事
Android2016.09.29JSONExportにコントリビュートしました
Android2015.09.09LinkedIn製AndroidセキュリティチェックTool、QARKを使ってみた
Android2015.06.09Android Design Support Libraryを使ってマテリアル化する
Android2015.02.23Android StudioでテストライブラリEspressoを使用する