测试您的服务

如果您要实现本地 Service 作为应用的组件,请执行以下操作: 可以创建插桩测试来验证其行为是否正确。

AndroidX Test 提供了一个 API,用于在 Service 隔离。ServiceTestRule 类是 JUnit 4 规则,用于启动 服务,并在单元测试方法运行后关停该服务 测试完成。如需详细了解 JUnit 4 规则,请参阅 JUnit 文档

设置测试环境

在为服务构建集成测试之前,请务必配置 进行插桩测试,如针对 AndroidX Test

创建服务的集成测试

您的集成测试应编写为 JUnit 4 测试类。了解详情 有关创建 JUnit 4 测试类以及如何使用 JUnit 4 断言方法的信息,请参阅 创建插桩测试类

使用 @Rule 在测试中创建 ServiceTestRule 实例 注解。

KotlinJava

@get:Rule
val serviceRule = ServiceTestRule()


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

以下示例展示了如何针对 服务。测试方法 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);
}

其他资源

如需详细了解此主题,请参阅下面列出的其他资源。

示例