בדיקת השירות

אם אתם מטמיעים Service מקומי כרכיב באפליקציה, עליכם יכול ליצור בדיקות אינסטרומנטליות כדי לאמת שאופן הפעולה שלו נכון.

בדיקת AndroidX מספקת API לבדיקת האובייקטים של Service ב- של טרנספורמר. המחלקה ServiceTestRule היא כלל JUnit 4 שמתחיל את לפני שהשיטות של בדיקת היחידה מופעלות, ומכבה את השירות לאחר מכן הבדיקות הושלמו. למידע נוסף על כללי JUnit 4, ראו JUnit תיעוד.

הגדרת סביבת הבדיקה

לפני שיוצרים את בדיקת השילוב של השירות, חשוב להגדיר את הפרויקט שלכם לבדיקות אינסטרומנטליות, כפי שמתואר במאמר הגדרת פרויקט עבור בדיקת AndroidX.

יצירת בדיקת שילוב לשירותים

צריך לכתוב את בדיקת השילוב ככיתת בדיקה של JUnit 4. מידע נוסף על יצירת מחלקות בדיקה ב-JUnit 4 ושימוש בשיטות טענת נכוֹנוּת (assertion) של 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);
}

מקורות מידע נוספים

כדי לקבל מידע נוסף בנושא, אפשר לעיין במקורות המידע הנוספים הבאים.

דוגמיות