使用 AndroidX Test 的 JUnit4 規則

AndroidX Test 包含一組 JUnit 規則,供您與 AndroidJUnitRunner 搭配使用。JUnit 規則提供更多彈性,並減少測試所需的樣板程式碼。例如,這些模組可用來啟動特定活動。

ActivityScenarioRule

這項規則提供單一活動的功能測試。規則會在每個含有 @Test 註解的測試之前,以及任何含有 @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 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 的簡易用法。