测试您的服务

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

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

设置测试环境

在为服务构建集成测试之前,请务必按照针对 AndroidX Test 设置项目中的说明,为插桩测试配置项目。

创建服务的集成测试

您的集成测试应编写为 JUnit 4 测试类。如需详细了解如何创建 JUnit 4 测试类和使用 JUnit 4 断言方法,请参阅创建插桩测试类。

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

@get:Rule
val serviceRule = ServiceTestRule()

以下示例展示了如何为服务实现集成测试。测试方法 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)))
}

其他资源

如需详细了解此主题,请参阅以下其他资源。

示例