AndroidX Test の JUnit4 ルール

AndroidX Test には、一連の JUnit ルールが組み込まれており、 AndroidJUnitRunner:JUnit ルールを使用すると、柔軟性が高くなり、 テストに必要なボイラープレート コード。たとえば、 できます。

ActivityScenarioRule

このルールは、単一アクティビティの機能テストを提供します。ルールが起動され、 @Test アノテーションが付けられた各テストの前と、それより前の @Before アノテーションが付けられた任意のメソッド。ルールは、 テストが完了し、@After アノテーション付きのメソッドがすべて終了しました。特定の 追加する場合は、API 呼び出しを実行可能なコールバックを 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

このルールにより、サービスの起動前にサービスを シャットダウンする必要は ありません次のコマンドでサービスを開始またはバインドできます。 ヘルパー メソッドの 1 つになります。テスト後に自動的に停止またはバインド解除される 完了し、@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 ルールを使用する方法の詳細については、 ご覧ください

ドキュメント

サンプル

  • BasicSample: ActivityScenarioRule の単純な使用方法。