Przetestuj usługę

Jeśli implementujesz lokalną aplikację (Service) jako część aplikacji: może tworzyć testy instrumentalne, aby sprawdzić, czy jego działanie jest prawidłowe.

AndroidX Test udostępnia interfejs API do testowania obiektów Service w izolacji użytkowników. Klasa ServiceTestRule to reguła JUnit 4, która zaczyna się przed uruchomieniem metod testów jednostkowych i wyłącza usługę po . Więcej informacji o regułach JUnit 4 znajdziesz w artykule JUnit dokumentacji.

Konfigurowanie środowiska testowego

Zanim utworzysz test integracji usługi, skonfiguruj do testów instrumentowanych zgodnie z opisem w sekcji Konfigurowanie projektu dla AndroidX Test.

Tworzenie testu integracji dla usług

Test integracji powinien być zapisany jako klasa testowa JUnit 4. Aby dowiedzieć się więcej, o tworzeniu klas testowych JUnit 4 i używaniu metod asercji JUnit 4 znajdziesz Tworzenie zinstrumentowanych zajęć testowych

Utwórz w teście instancję ServiceTestRule za pomocą interfejsu @Rule adnotacja.

KotlinJava

@get:Rule
val serviceRule = ServiceTestRule()


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

Poniższy przykład pokazuje, jak można wdrożyć test integracji dla posprzedażna. Metoda testowa testWithBoundService() sprawdza, czy aplikacja została powiązana z usługą lokalną oraz że interfejs usługi działa .

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

Dodatkowe materiały

Aby dowiedzieć się więcej na ten temat, zapoznaj się z tymi dodatkowymi materiałami.

Próbki