AndroidX Test 中的 JUnit4 规则

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

ActivityScenarioRule

此规则提供单个 Activity 的功能测试。该规则会在每个带有 @Test 注释的测试之前以及任何带有 @Before 注释的方法之前启动所选 Activity。该规则会在测试完成后以及所有带有 @After 注释的方法执行完毕后终止 Activity。要在您的测试逻辑中访问给定 Activity,请向 ActivityScenarioRule.getScenario().onActivity() 提供回调 runnable。

以下代码片段演示了如何将 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 的简单用法。