9、测试你的 Service

来源:互联网 发布:山东职业学院网络 编辑:程序博客网 时间:2024/05/29 16:16

测试你的 Service

如果您正在将一个本地 Service 作为您的应用程序中的一个组件实现,你应该测试这个 Service 以确保他不会以意外的方式运行。你可以创建一个 instrumented 单元测试 来验证 Service 的行为是否正确;例如,service 存储并返回了有效的数据并且正确的执行了数据操作。

Android 测试支持库 提供了独立的 API 用来测试你的 Service 对象。ServiceTestRule 类是一个 JUnit 4 rule,在你的单元测试方法运行之前,他将会启动你的 service ,然后在测试结束之后关闭 service. 通过使用这个测试 rule,可以确保在你的测试方法运行之前 service 始终建立连接。要想了解更多 JUnit 4 rules,请看 JUnit 文档。

注意:ServiceTestRule 类不支持 IntentService 对象的测试。如果你想测试一个 IntentService 对象,你应该将逻辑封装到一个独立的类中,并且创建相关的单元测试。

设置你的测试环境

在你开始构建对 service 的集成测试之前,请确保按照 测试入门 里面描述的为您的项目配置测试。

创建一个 Services 集成测试

你的集成测试应该被编写成一个 JUnit 4 测试类。要想了解更多关于创建 JUnit 4 测试类和使用 JUnit 4 assertion 方法,请看 创建一个 Instrumented 单元测试类.

要想为你的 service 创建一个集成测试,请在你的测试类定义的开头添加 @RunWith(AndroidJUnit4.class) 注解。你也需要确认 Android 测试支持库提供的 AndroidJUnitRunner 类是你默认的测试运行器。[运行 Instrumented 单元测试] 描述了更多关于这个步骤的内容。

接下来,通过使用 @Rule 注解创建一个你的测试中的 ServiceTestRule 实例。

@Rulepublic final ServiceTestRule mServiceRule = new ServiceTestRule();

下面的例子展示了你应该如何实现一个 service 的集成测试。 testWithBoundService 这个测试方法验证了你的应用是否成功的与本地 service 绑定并且这个 service 接口的行为是否正确。

@Testpublic void testWithBoundService() throws TimeoutException {    // Create the service Intent.    Intent serviceIntent =            new Intent(InstrumentationRegistry.getTargetContext(),                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 = mServiceRule.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(), is(any(Integer.class)));}

运行 Services 的集成测试

你可以从 Android Studio 或者命令行运行 UI Automator 测试。确保将 AndroidJUnitRunner 作为你工程默认的 instrumentation 工具。

要想运行你的 UI Automator 测试,请按照 测试入门 中的描述的运行 instrumented 测试的步骤。

原创粉丝点击