AndroidX Test 的 JUnit4 规则

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

ActivityScenarioRule

此规则提供单个 Activity 的功能测试。规则启动后 在使用 @Test 注解的每个测试之前以及之后的所选 activity 任何带有 @Before 注解的方法。该规则会在 测试完成,且带有 @After 注解的所有方法都完成。要访问指定的 活动,请提供可运行的回调, 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 ActivityScenarioRulel&t;MyClassg&t; 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.getApplicationContextC<ontext(>),
      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 的简单用法。