LoginSignup
7
7

More than 5 years have passed since last update.

Android Studio 1.4でJUnit4

Last updated at Posted at 2015-10-15

Androidもやっとこさ正式にJUnit4に対応したとのことで、Test Support Libraryを使った現時点でのおまじない手順をメモっておきます。(おそらくしばらくは変わらないんじゃないかな…)

環境

  • Android Studio 1.4

手順

  • build.gradleに1+2行追加してgradle syncする。
build.gradle
android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"  
    }
}

dependencies {
    androidTestCompile 'com.android.support.test:runner:0.4'
    androidTestCompile 'com.android.support.test:rules:0.4'
}
  • テストクラスを生成する。自動生成ウィザードを使いたい場合にはテスト対象のクラス名を選択した状態でoption+Enter -> Create Testを選ぶ。ウィザードではJUnit4を選択する。
  • 実行したいテストメソッドを含むクラスの宣言に@RunWith(AndroidJUnit4.class)というアノテーションをつける。
  • JUnit4なのでテストメソッドには@Testアノテーションをつける。
  • JUnit4ではJUnit3のようにTestCaseクラスを継承しないので、assert*メソッドがそのままでは自動補完されない。assertまで入力し、Ctrl+spaceを2回押して候補を表示させた後、option+Enter -> import staticallyを選択し、static importする。
HogeTest.java
package youten.redo.junit4;

import android.support.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import static junit.framework.Assert.assertEquals;

@RunWith(AndroidJUnit4.class)
public class HogeTest {

    @Test
    public void testHoge() throws Exception {
        int expected = 2;
        int actual = 1 + 1;
        assertEquals(expected, actual);
    }

}

【よもやま】
手元の環境では、RunWithアノテーションはなくても動作してしまいました。特別なアノテーションを使うとか、古いAndroidバージョンのデバイスでJUnit4したい際でなければだいじょうぶなのでしょうか?詳細は追っていませんあしからず。

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