Android Studio 1.5 + JUnit4 + Espressoでテストする


テストコードも書かなきゃね!ってことで、Android Studio 1.5 + JUnit4 + Espresso でテストの書き方覚書。

Projectを作成する

New Project -> Blank Activityでプロジェクトを作成します。FloatingActionButtonが表示されるActivityが生成されます。

Gradleの編集

抜粋です。

bundle.gradle
android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test:runner:0.4'
    androidTestCompile 'com.android.support.test:rules:0.4'
    androidTestCompile 'com.android.support:support-annotations:23.1.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'

    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

Activityの編集

単純にtrueを返すだけのメソッドを追加

MainActivity.java
    public boolean testMethod() {
        return true;
    }

テストコードの生成

MainActivityのクラス名にカーソルを合わせ、Option + Enterでメニューを表示、Create Testを選択します。

JUnit4を選択し、Class Nameを入力、テストしたいメソッドを下部より選択し、OKを押すとテストコードの雛形が生成されます。

テストコードの編集

MainActivityTest.java
package jp.qrnk.testapplication;

import android.support.test.espresso.Espresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.matcher.ViewMatchers.withId;

/**
 * Created by Teppei Okazaki.
 */
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {

    @Rule
    public ActivityTestRule<MainActivity> activityTestRule =
            new ActivityTestRule<>(MainActivity.class);

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testTestMethod() throws Exception {
        Assert.assertTrue(activityTestRule.getActivity().testMethod());

        // ActivityのFloatingActionButtonを取得して
        // クリックイベントを発生させてる
        Espresso.onView(withId(R.id.fab)).perform(click());
    }

}

各Annotationの説明はこちらが詳しいです。

実行

上部メニューからEdit Configurationを選択

➕メニューを選択しAndroid Testsを新規作成

これで実行すると、一瞬SnackBarが表示されてすぐテストが終了します。

終わりに

設定まわりと、JUnit4、Espressoのさわり部分について記載しました。テストって大事なのはわかるのですが、工数面々で折り合いがつかないことがありますよね。。。せめて外部システムとの接続部分についてはテストを書いていきたい所存です。

アプリ作りました。

NewsFeeder です。
サクッと今注目されている記事を見るのに便利です。
iOSは弊社インターンが開発し、現在申請中です。

お仕事募集しております

株式会社クランクでは、お仕事を募集しております。
サーバーサイド、クライアントサイド(JS, iOS, Android)を一貫して開発可能です。
弊社サイトにて案件実績を掲載しております。
またパートナー(フリーランス)、バイト、インターンの募集も行ってます。
エンジニア、サイクリストからのメッセージお待ちしております。