اختبار الخدمة

إذا كنت تنفِّذ Service محليًّا كمكوِّن في تطبيقك، يمكنك إنشاء اختبارات مُعدّة للتحقّق من صحة سلوكها.

يوفّر اختبار AndroidX واجهة برمجة تطبيقات لاختبار عناصر Service في وضع عزل. الفئة ServiceTestRule هي قاعدة JUnit 4 التي تبدأ الخدمة قبل تشغيل طرق اختبار الوحدات، وتوقِف الخدمة بعد اكتمال الاختبارات. لمزيد من المعلومات حول قواعد JUnit 4، يُرجى مراجعة وثائق JUnit.

إعداد بيئة الاختبار

قبل إنشاء اختبار دمج للخدمة، تأكَّد من ضبط مشروعك للاختبارات المساعِدة على النحو الموضّح في إعداد المشروع على AndroidX Test.

إنشاء اختبار دمج للخدمات

يجب كتابة اختبار التكامل كفئة اختبار JUnit 4. لمعرفة المزيد من المعلومات حول إنشاء صفوف اختبار JUnit 4 واستخدام طرق تأكيد JUnit 4، راجع إنشاء فئة اختبار مسندة.

يمكنك إنشاء مثيل ServiceTestRule في الاختبار باستخدام التعليق التوضيحي @Rule.

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

مراجع إضافية

لمعرفة المزيد عن هذا الموضوع، يُرجى الرجوع إلى المراجع الإضافية التالية.

عيّنات