测试您的服务

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

AndroidX Test 提供了一个 API,用于在隔离时测试 Service 对象。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);
}

其他资源

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

示例