Testar o serviço

Se você estiver implementando um Service local como componente do app, crie testes instrumentados para verificar se o comportamento dele está correto.

O AndroidX Test oferece uma API para testar os objetos Service isoladamente. A classe ServiceTestRule é uma regra JUnit 4 que inicia o serviço antes da execução dos métodos de teste de unidade e encerra o serviço após a conclusão dos testes. Para saber mais sobre as regras JUnit 4, consulte a documentação do JUnit (em inglês).

Configurar o ambiente de teste

Antes de criar seu teste de integração para o serviço, configure seu projeto para testes de instrumentação, conforme descrito em Configurar projeto para teste do AndroidX.

Criar um teste de integração para serviços

Crie seu teste de integração como uma classe de teste do JUnit4. Para saber mais sobre como criar classes de teste do JUnit 4 e usar os métodos de declaração do JUnit 4, consulte Criar uma classe de teste de instrumentação.

Crie uma instância ServiceTestRule no teste usando a anotação @Rule.

Kotlin


@get:Rule
val serviceRule = ServiceTestRule()

Java


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

O exemplo a seguir mostra como implementar um teste de integração para um serviço. O método de teste testWithBoundService() verifica se o app está vinculado a um serviço local e se a interface do serviço se comporta corretamente.

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

Outros recursos

Para saber mais sobre esse assunto, consulte os recursos a seguir.

Exemplos