AndroidX Test 包含需要与 AndroidJUnitRunner
一起使用的一组 JUnit 规则。JUnit 规则可提供更高的灵活性,并减少测试中所需的样板代码。
ActivityTestRule
此规则提供单个 Activity 的功能测试。被测 Activity 会在带有 @Test
注释的每个测试运行之前以及带有 @Before
注释的所有方法运行之前启动。它会在测试完成并且带有 @After
注释的所有方法结束后终止。如需在测试逻辑中访问被测的 Activity,请调用 ActivityTestRule.getActivity()
。
注意:AndroidX Test 还包含一个 API ActivityScenario
,它目前处于 Beta 版阶段。此 API 可在各种测试环境中运行,并在使用它的测试中提供线程安全。
我们建议您试用此 API,看看它如何帮助您推动应用 Activity 的生命周期。
以下代码段演示了如何将 ActivityTestRule
融入测试逻辑:
Kotlin
@RunWith(AndroidJUnit4::class.java) @LargeTest class MyClassTest { @get:Rule val activityRule = ActivityTestRule(MyClass::class.java) @Test fun myClassMethod_ReturnsTrue() { ... } }
Java
@RunWith(AndroidJUnit4.class) @LargeTest public class MyClassTest { @Rule public ActivityTestRule<MyClass> activityRule = new ActivityTestRule(MyClass.class); @Test public void myClassMethod_ReturnsTrue() { ... } }
ServiceTestRule
此规则提供了一种简化的机制,用于在测试之前启动服务以及在测试之后关闭服务。它还可以保证在启动服务或绑定到服务时成功连接该服务。您可以使用某个辅助程序方法启动或绑定服务。它会在测试完成并且带有 @After
注释的所有方法结束后自动停止或取消绑定。
Kotlin
@RunWith(AndroidJUnit4::class.java) @MediumTest class MyServiceTest { @get:Rule val serviceRule = ServiceTestRule() @Test fun testWithStartedService() { serviceRule.startService( Intent(ApplicationProvider.getApplicationContext<Context>(), MyService::class.java)) // Add your test code here. } @Test fun testWithBoundService() { val binder = serviceRule.bindService( Intent(ApplicationProvider.getApplicationContext(), MyService::class.java)) val service = (binder as MyService.LocalBinder).service assertThat(service.doSomethingToReturnTrue()).isTrue() } }
Java
@RunWith(AndroidJUnit4.class) @MediumTest public class MyServiceTest { @Rule public final ServiceTestRule serviceRule = new ServiceTestRule(); @Test public void testWithStartedService() { serviceRule.startService( new Intent(ApplicationProvider.getApplicationContext(), MyService.class)); // Add your test code here. } @Test public void testWithBoundService() { IBinder binder = serviceRule.bindService( new Intent(ApplicationProvider.getApplicationContext(), MyService.class)); MyService service = ((MyService.LocalBinder) binder).getService(); assertThat(service.doSomethingToReturnTrue()).isTrue(); } }
其他资源
如需详细了解如何在 Android 测试中使用 JUnit 规则,请参阅以下资源。
示例
- BasicSample:
ActivityTestRule
的简单用法。