AndroidX Test には、AndroidJUnitRunner
で使用される一連の JUnit ルールが含まれています。JUnit ルールはテストの柔軟性を高め、必要なボイラープレート コードを削減します。
ActivityTestRule
このルールは、単一アクティビティの機能テストを提供します。テスト対象のアクティビティは、@Test
アノテーションが付いたテストと @Before
アノテーションが付いたメソッドが開始される前に起動されます。テストが完了して @After
アノテーションの付いたメソッドがすべて終了すると、アクティビティが停止します。テストロジックでテスト対象のアクティビティにアクセスするには、ActivityTestRule.getActivity()
を呼び出します。
注: AndroidX Test には、現在はベータ版の ActivityScenario
API も含まれています。この API はさまざまなテスト環境で動作し、この API を使用するテストのスレッドの安全性を確保します。
この API を使ってみて、アプリのアクティビティ ライフサイクルの促進にどの程度役立つか確認することをおすすめします。
次のコード スニペットは、ActivityTestRule
をテストロジックに組み込む方法を示しています。
Kotlin
@RunWith(AndroidJUnit4::class.java) @LargeTest class MyClassTest { @get:Rule val activityRule = ActivityTestRule(MyClass::class.java) @Test fun myClassMethod_ReturnsTrue() { ... } }
Java
@RunWith(AndroidJUnit4.class) @LargeTest public class MyClassTest { @Rule public ActivityTestRule<MyClass> activityRule = new ActivityTestRule(MyClass.class); @Test public void myClassMethod_ReturnsTrue() { ... } }
ServiceTestRule
このルールは、テストの前後にサービスを開始およびシャットダウンするためのシンプルなメカニズムを提供します。また、サービスの開始時またはバインド時にサービスが正常に接続されることを保証します。サービスが、ヘルパー メソッドの 1 つを使用して開始またはバインドされます。テストが完了して @After
アノテーション付きのメソッドがすべて終了すると、サービスが自動的に停止またはバインド解除されます。
Kotlin
@RunWith(AndroidJUnit4::class.java) @MediumTest class MyServiceTest { @get:Rule val serviceRule = ServiceTestRule() @Test fun testWithStartedService() { serviceRule.startService( Intent(ApplicationProvider.getApplicationContext<Context>(), MyService::class.java)) // Add your test code here. } @Test fun testWithBoundService() { val binder = serviceRule.bindService( Intent(ApplicationProvider.getApplicationContext(), MyService::class.java)) val service = (binder as MyService.LocalBinder).service assertThat(service.doSomethingToReturnTrue()).isTrue() } }
Java
@RunWith(AndroidJUnit4.class) @MediumTest public class MyServiceTest { @Rule public final ServiceTestRule serviceRule = new ServiceTestRule(); @Test public void testWithStartedService() { serviceRule.startService( new Intent(ApplicationProvider.getApplicationContext(), MyService.class)); // Add your test code here. } @Test public void testWithBoundService() { IBinder binder = serviceRule.bindService( new Intent(ApplicationProvider.getApplicationContext(), MyService.class)); MyService service = ((MyService.LocalBinder) binder).getService(); assertThat(service.doSomethingToReturnTrue()).isTrue(); } }
参考情報
Android テストで JUnit ルールを使用する方法の詳細については、次のリソースをご覧ください。
サンプル
- BasicSample:
ActivityTestRule
の簡単な使用方法。