AndroidX Test の JUnit4 ルール

AndroidX Test には、AndroidJUnitRunner で使用される一連の JUnit ルールが含まれています。JUnit ルールを使用することで柔軟性が向上し、テストで必要なボイラープレート コードを減らすことができます。たとえば、特定のアクティビティを開始するために使用できます。

ActivityScenarioRule

このルールは、単一アクティビティの機能テストを提供します。このルールにより、選択されたアクティビティが、@Test アノテーション付きの各テストの前や、@Before アノテーションを付けたメソッドの前に起動します。このルールは、テストが完了し、@After アノテーション付きのすべてのメソッドが終了すると、アクティビティを終了します。テストロジック内の特定のアクティビティにアクセスするには、ActivityScenarioRule.getScenario().onActivity() に実行可能なコールバックを提供します。

次のコード スニペットは、ActivityScenarioRule をテストロジックに組み込む方法を示しています。

Kotlin


@RunWith(AndroidJUnit4::class.java)
@LargeTest
class MyClassTest {
  @get:Rule
  val activityRule = ActivityScenarioRule(MyClass::class.java)

  @Test fun myClassMethod_ReturnsTrue() {
    activityRule.scenario.onActivity { … } // Optionally, access the activity.
   }
}

Java


public class MyClassTest {
    @Rule
    public ActivityScenarioRule<MyClass> activityRule =
            new ActivityScenarioRule(MyClass.class);

    @Test
    public void myClassMethod_ReturnsTrue() { ... }
}

ServiceTestRule

このルールは、テストの前にサービスを起動し、テストの前後にサービスをシャットダウンするシンプルなメカニズムを提供します。いずれかのヘルパー メソッドを使用して、サービスを開始またはバインドできます。テストが完了し、@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: ActivityScenarioRule の簡単な使用方法。