サービスをテストする

ローカルの Service をアプリのコンポーネントとして実装する場合、インストルメンテーション テストを作成して、その動作が正しいことを確認できます。

AndroidX Test には、Service オブジェクトを隔離状態でテストするための API が用意されています。ServiceTestRule クラスは、単体テストメソッドが実行される前にサービスを開始し、テストの完了後にサービスをシャットダウンする JUnit 4 ルールです。JUnit 4 ルールの詳細については、JUnit のドキュメントをご覧ください。

テスト環境をセットアップする

サービスの統合テストを作成する前に、AndroidX Test 用にプロジェクトをセットアップするの説明に沿って、インストルメンテーション テスト用のプロジェクトを設定してください。

サービスの統合テストを作成する

統合テストは、JUnit 4 テストクラスとして作成する必要があります。JUnit 4 テストクラスの作成と JUnit 4 アサーション メソッドの使用の詳細については、インストルメンテーション テストクラスを作成するをご覧ください。

@Rule アノテーションを使用して、テストで ServiceTestRule インスタンスを作成します。

Kotlin


@get:Rule
val serviceRule = ServiceTestRule()

Java


@Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();

次の例は、サービスの統合テストを実装する方法を示しています。テストメソッド testWithBoundService() は、アプリがローカル サービスに正常にバインドされ、サービス インターフェースが正しく動作することを検証します。

Kotlin


@Test
@Throws(TimeoutException::class)
fun testWithBoundService() {
  // Create the service Intent.
  val serviceIntent = Intent(
      ApplicationProvider.getApplicationContext<Context>(),
      LocalService::class.java
  ).apply {
    // Data can be passed to the service via the Intent.
    putExtra(SEED_KEY, 42L)
  }

  // Bind the service and grab a reference to the binder.
  val binder: IBinder = serviceRule.bindService(serviceIntent)

  // Get the reference to the service, or you can call
  // public methods on the binder directly.
  val service: LocalService = (binder as LocalService.LocalBinder).getService()

  // Verify that the service is working correctly.
  assertThat(service.getRandomInt(), `is`(any(Int::class.java)))
}

Java


@Test
public void testWithBoundService() throws TimeoutException {
  // Create the service Intent.
  Intent serviceIntent =
      new Intent(ApplicationProvider.getApplicationContext(),
        LocalService.class);

  // Data can be passed to the service via the Intent.
  serviceIntent.putExtra(LocalService.SEED_KEY, 42L);

  // Bind the service and grab a reference to the binder.
  IBinder binder = serviceRule.bindService(serviceIntent);

  // Get the reference to the service, or you can call
  // public methods on the binder directly.
  LocalService service =
      ((LocalService.LocalBinder) binder).getService();

  // Verify that the service is working correctly.
  assertThat(service.getRandomInt()).isAssignableTo(Integer.class);
}

参考情報

このトピックの詳細については、以下の参考情報をご覧ください。

サンプル