AndroidX 테스트에 JUnit4 규칙 사용

AndroidX 테스트에는 AndroidJUnitRunner와 함께 사용되는 JUnit 규칙 세트가 포함되어 있습니다. 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 규칙을 사용하는 방법에 관한 자세한 내용은 다음 리소스를 참조하세요.

도움말

샘플

  • BasicSample: ActivityScenarioRule의 간단한 사용법입니다.