如果您正在将本地 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); }
其他资源
要详细了解此主题,请查阅以下其他资源。