使用 AndroidX Test 的 JUnit4 規則

AndroidX Test 包含一組 JUnit 規則,可與 AndroidJUnitRunner。JUnit 規則可提高彈性,並減少 測試中所需的樣板程式碼。舉例來說,這類函式可用來啟動 特定活動。

活動情境規則

此規則提供單一活動的功能測試。啟動規則 在每個加上 @Test 註解的測試之前以及 任何加上 @Before 註解的方法。規則會在 測試完成,且所有加上 @After 註解的方法都已完成。若要存取提供的 請在測試邏輯中為活動提供可執行的回呼,以便對 ActivityScenarioRule.getScenario().onActivity()

下列程式碼片段說明如何納入 將 ActivityScenarioRule 加入測試邏輯:

KotlinJava

@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.
   
}
}


public class MyClassTest {
   
@Rule
   
public ActivityScenarioRule<MyClass> activityRule =
           
new ActivityScenarioRule(MyClass.class);

   
@Test
   
public void myClassMethod_ReturnsTrue() { ... }
}

ServiceTestRule

此規則可提供簡化的機制,讓您可在 並在測試前後關閉您可以使用 其中一種輔助方法測試完成後會自動停止或解除繫結 已完成,加上 @After 註解的所有方法均已完成。

KotlinJava

@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()
 
}
}


@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 的簡單用法。