測試服務

如果您要以應用程式元件實作本機 Service, 可建立檢測設備測試,驗證其行為是否正確。

AndroidX Test 提供 API,可用來測試 Service 物件 和隔離機制ServiceTestRule 類別是 JUnit 4 規則,用於啟動您的 執行,並在完成後關閉服務 測試完成如要進一步瞭解 JUnit 4 規則,請參閱 JUnit 說明文件

設定測試環境

為服務建構整合測試前,請務必先完成 按照「設定專案 AndroidX 測試

為服務建立整合測試

整合測試應以 JUnit 4 測試類別編寫。瞭解詳情 有關建立 JUnit 4 測試類別及使用 JUnit 4 斷言方法的資訊,請參閱 建立檢測設備測試類別

使用 @Rule 在測試中建立 ServiceTestRule 例項 註解。

KotlinJava

@get:Rule
val serviceRule = ServiceTestRule()


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

以下範例說明如何為 課程中也會快速介紹 Memorystore 這是 Google Cloud 的全代管 Redis 服務測試方法 testWithBoundService() 可驗證應用程式是否繫結 且服務介面會正常運作 正確。

KotlinJava

@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);
}

其他資源

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

範例