Hizmetinizi test etme

Uygulamanızın bileşeni olarak yerel bir Service kullanıyorsanız , davranışının doğruluğunu onaylamak için araçlı testler oluşturabilir.

AndroidX Test, Service nesnelerinizi izole ediliyor. ServiceTestRule sınıfı, test yöntemleriniz çalıştırılmadan önce çalışır veya tamamlandı. JUnit 4 kuralları hakkında daha fazla bilgi edinmek için JUnit 4 dokümanlarına göz atın.

Test ortamınızı ayarlama

Hizmet için entegrasyon testinizi oluşturmadan önce, Projeyi her aşamaya uygun şekilde ayarlama AndroidX Testi.

Hizmetler için entegrasyon testi oluşturma

Entegrasyon testiniz, JUnit 4 test sınıfı olarak yazılmalıdır. Daha fazla bilgi edinmek için JUnit 4 test sınıfları oluşturma ve JUnit 4 onay yöntemlerini kullanma hakkında bilgi için Araçlı test sınıfı oluşturun.

@Rule kullanarak testinizde bir ServiceTestRule örneği oluşturun ek açıklaması da yer alır.

KotlinJava

@get:Rule
val serviceRule = ServiceTestRule()


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

Aşağıdaki örnekte, bir web sitesi için entegrasyon testini nasıl uygulayabileceğiniz geliştirmenizi sağlar. testWithBoundService() test yöntemi, uygulamanın bağlandığını doğrular başarılı bir şekilde bağlandığını ve hizmet arayüzünün, sağlayabilir.

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

Ek kaynaklar

Aşağıdaki ek kaynaklara göz atarak bu konu hakkında daha fazla bilgi edinebilirsiniz.

Örnekler