ローカル Service
をアプリのコンポーネントとして実装する場合は、次の操作を行います。
インストルメンテーション テストを作成して、動作が正しいことを確認できます。
AndroidX Test には、Service
オブジェクトをテストするための API が用意されています。
分離しますServiceTestRule
クラスは JUnit 4 ルールで、
単体テストメソッドを実行する前にサービスを開始し、終了したらサービスをシャットダウンします。
テスト完了です。JUnit 4 ルールの詳細については、JUnit 4 ルールの
ドキュメントをご覧ください。
テスト環境をセットアップする
サービスの統合テストを構築する前に、 インストルメンテーション テスト用にプロジェクトを作成します。プロジェクトの設定 AndroidX Test
サービスの統合テストを作成する
統合テストは、JUnit 4 テストクラスとして作成する必要があります。関連資料 JUnit 4 テストクラスの作成と JUnit 4 アサーション メソッドの使用方法については、以下をご覧ください。 インストルメンテーション テストクラスを作成する。
@Rule
を使用してテストに ServiceTestRule
インスタンスを作成する
アノテーション。
@get:Rule
val serviceRule = ServiceTestRule()
@Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();
次の例は、Google Cloud プロジェクト用の統合テストを実装する方法を示しています。
あります。テストメソッド testWithBoundService()
は、アプリがバインドされていることを確認する
正常にローカル サービスに接続でき、サービス インターフェースが
確認します。
@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)))
}
@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);
}
参考情報
このトピックについて詳しくは、以下の参考情報をご覧ください。