2015年8月3日月曜日

Android JUnit 4 形式のテストにする

InstrumentationTestRunner は JUnit 3 しかサポートしていませんが、Android Testing Support Library に含まれる AndroidJUnitRunner を使うと JUnit 4-compatible なテストを実行することができます。
(JUnit 3 と JUnit 4.10 までの JUnit 4 互換)

Android 2.2 (API Level 8) 以上が必要です。

▪️ Setup dependencies { androidTestCompile 'com.android.support.test:runner:0.3' // to use JUnit 4 rules androidTestCompile 'com.android.support.test:rules:0.3' } android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } }

▪️ Usage

- JUnit 4 で実装されたテストクラスには @RunWith(AndroidJUnit4.class) をつける
- テスト対象メソッドには @Test をつける
- setUp() を Override し、public に変更し @Before をつける
- tearDown() を Override し、public に変更し @After をつける
- 必要に応じて AndroidTestCase.setContext(InstrumentationRegistry.getContext()) や InstrumentationTestCase.injectInstrumentation(InstrumentationRegistry.getInstrumentation()) を setUp() で行う

@RunWith(AndroidJUnit4.class) public class SimpleTest extends AndroidTestCase { @Before public void setUp() throws Exception { super.setUp(); setContext(InstrumentationRegistry.getContext()); } @Test public void testSample() { assertNotNull(getContext()); } @After public void tearDown() throws Exception { super.tearDown(); } } - InstrumentationRegistryでテスト実行時の情報を取得できる
- InstrumentationRegistry.getContext() : instrumentation のパッケージContext
- InstrumentationRegistry.getTargetContext() : テスト対象のアプリケーションのContext
- InstrumentationRegistry.getInstrumentation() : 実行中の instrumentation


▪️ Test filtering

- @RequiresDevice : 実機でのみ実行(エミュレータでは実行しない)
- @SdkSuppress : 指定された API Level より低い場合実行しない、@SdkSuppress(minSdkVersion=21) など
- @SmallTest, @MediumTest, @LargeTest : テストにどのくらいかかるかのクラス分け


▪️ 参考

- http://developer.android.com/tools/testing-support-library/index.html