서비스 테스트

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

AndroidX 테스트는 다음에서 Service 객체를 테스트하는 API를 제공합니다. 격리합니다 ServiceTestRule 클래스는 서비스를 종료하고 테스트 실행 후에 서비스를 종료합니다. 테스트가 완료됩니다. JUnit 4 규칙에 관한 자세한 내용은 JUnit 문서를 참조하세요.

테스트 환경 설정

서비스의 통합 테스트를 빌드하기 전에 다음 프로젝트에 프로젝트 설정: AndroidX 테스트를 참조하세요.

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

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

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

Kotlin자바

@get:Rule
val serviceRule = ServiceTestRule()


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

다음 예는 있습니다. 테스트 메서드 testWithBoundService()는 앱이 바인딩되는지 확인합니다. 서비스 인터페이스가 로컬 서비스에 성공적으로 있습니다.

KotlinJava

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


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

추가 리소스

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

샘플