AndroidX Test 的 JUnit4 规则

AndroidX Test 包含一组要与 AndroidJUnitRunner 一起使用的 JUnit 规则。JUnit 规则可提供更高的灵活性,并减少测试中所需的样板代码。例如,它们可用于启动特定的 activity。

ActivityScenarioRule

此规则提供单个 Activity 的功能测试。该规则会在带有 @Test 注解的每个测试之前以及带有 @Before 注解的任何方法之前启动所选的 activity。该规则会在测试完成并且带有 @After 注解的所有方法完成后终止 activity。如需访问测试逻辑中的指定 activity,请提供可运行到 ActivityScenarioRule.getScenario().onActivity() 的回调。

以下代码段演示了如何将 ActivityScenarioRule 整合到测试逻辑中:

Kotlin


@RunWith(AndroidJUnit4::class.java)
@LargeTest
class MyClassTest {
  @get:Rule
  val activityRule = ActivityScenarioRule(MyClass::class.java)

  @Test fun myClassMethod_ReturnsTrue() {
    activityRule.scenario.onActivity { … } // Optionally, access the activity.
   }
}

Java


public class MyClassTest {
    @Rule
    public ActivityScenarioRule<MyClass> activityRule =
            new ActivityScenarioRule(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 规则,请参阅以下资源。

文档

示例

  • BasicSampleActivityScenarioRule 的简单用法。