서비스 테스트

로컬 Service를 앱의 구성요소로 구현하는 경우 계측 테스트를 만들어 동작이 올바른지 확인할 수 있습니다.

AndroidX 테스트Service 객체를 격리된 상태로 테스트하는 API를 제공합니다. ServiceTestRule 클래스는 단위 테스트 메서드가 실행되기 전에 서비스를 시작하고 테스트가 완료된 후 서비스를 종료하는 JUnit 4 규칙입니다. JUnit 4 규칙에 관해 자세히 알아보려면 JUnit 문서를 참고하세요.

테스트 환경 설정

서비스의 통합 테스트를 빌드하기 전에 AndroidX 테스트용 프로젝트 설정에 설명된 대로 계측 테스트용 프로젝트를 구성해야 합니다.

서비스의 통합 테스트 만들기

통합 테스트는 JUnit 4 테스트 클래스로 작성해야 합니다. JUnit 4 테스트 클래스를 만드는 방법과 JUnit 4 어설션 메서드를 사용하는 방법을 자세히 알아보려면 계측 테스트 클래스 만들기를 참고하세요.

@Rule 주석을 사용하여 테스트에 ServiceTestRule 인스턴스를 만듭니다.

Kotlin


@get:Rule
val serviceRule = ServiceTestRule()

Java


@Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();

다음 예는 서비스의 통합 테스트를 구현하는 방법을 보여줍니다. 테스트 메서드 testWithBoundService()는 앱이 로컬 서비스에 성공적으로 바인딩되고 서비스 인터페이스가 올바르게 작동하는지 확인합니다.

Kotlin


@Test
@Throws(TimeoutException::class)
fun testWithBoundService() {
  // Create the service Intent.
  val serviceIntent = Intent(
      ApplicationProvider.getApplicationContext<Context>(),
      LocalService::class.java
  ).apply {
    // Data can be passed to the service via the Intent.
    putExtra(SEED_KEY, 42L)
  }

  // Bind the service and grab a reference to the binder.
  val binder: IBinder = serviceRule.bindService(serviceIntent)

  // Get the reference to the service, or you can call
  // public methods on the binder directly.
  val service: LocalService = (binder as LocalService.LocalBinder).getService()

  // Verify that the service is working correctly.
  assertThat(service.getRandomInt(), `is`(any(Int::class.java)))
}

Java


@Test
public void testWithBoundService() throws TimeoutException {
  // Create the service Intent.
  Intent serviceIntent =
      new Intent(ApplicationProvider.getApplicationContext(),
        LocalService.class);

  // Data can be passed to the service via the Intent.
  serviceIntent.putExtra(LocalService.SEED_KEY, 42L);

  // Bind the service and grab a reference to the binder.
  IBinder binder = serviceRule.bindService(serviceIntent);

  // Get the reference to the service, or you can call
  // public methods on the binder directly.
  LocalService service =
      ((LocalService.LocalBinder) binder).getService();

  // Verify that the service is working correctly.
  assertThat(service.getRandomInt()).isAssignableTo(Integer.class);
}

추가 리소스

이 주제에 관해 자세히 알아보려면 다음 추가 리소스를 참고하세요.

샘플