測試服務

如果您要將本機 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);
}

其他資源

如要進一步瞭解這個主題,請參閱下列其他資源。

範例