测试您的服务

如果您要实现将本地 Service 作为应用的组件,则应对 Service 进行测试,以确保其不会出现意外行为。您可以创建插桩单元测试以验证 Service 的行为是否正确;例如,服务是否存储和返回有效的数据值并正确执行数据操作。

AndroidX Test 提供了一个 API,用于在隔离的环境中测试 Service 对象。ServiceTestRule 类是一个 JUnit 4 规则,可在单元测试方法运行之前启动服务,并在测试完成后关闭服务。通过使用此测试规则,您可确保始终在测试方法运行之前建立与服务的连接。如需详细了解 JUnit 4 规则,请参阅 JUnit 文档

注意ServiceTestRule 类不支持测试 IntentService 对象。如果您需要测试 IntentService 对象,应将逻辑封装在一个单独的类中,并创建相应的单元测试。

设置测试环境

在构建服务的集成测试之前,请务必针对插桩测试配置项目,如针对 AndroidX Test 设置项目中所述。

创建服务的集成测试

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

如需创建服务的集成测试,请在测试类定义的开头添加 @RunWith(AndroidJUnit4::class) 注释。您还需要将 AndroidX Test 提供的 AndroidJUnitRunner 类指定为默认测试运行程序。运行插桩单元测试中对此步骤进行了更详细的说明。

接下来,使用 @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);
    }
    

运行服务的集成测试

您可以通过 Android Studio 或命令行运行集成测试。请务必在项目中将 AndroidJUnitRunner 指定为默认插桩测试运行程序。

如需运行服务的集成测试,请按照测试入门中所述的插桩测试运行步骤进行操作。

您还应阅读服务

其他资源

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

示例