כללי JUnit4 עם בדיקת AndroidX

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

תרחיש הפעילות

הכלל הזה מספק בדיקה פונקציונליות של פעילות יחידה. הכלל מופעל הפעילות שנבחרה לפני כל בדיקה שנוספה באמצעות @Test, וגם לפניה כל method שמסומנת ב-@Before. הכלל מסיים את הפעילות אחרי הבדיקות שהושלמו וכל השיטות שנוספו להן הערות עם סיום ה-@After. כדי לגשת אל פעילות בלוגיקת הבדיקה, ספק קריאה חוזרת (callback) שאפשר להריץ ActivityScenarioRule.getScenario().onActivity()

קטע הקוד הבא מדגים איך להטמיע ActivityScenarioRule בלוגיקת הבדיקה:

Kotlin

@RunWith(AndroidJUnit4::class.java)
@LargeTest
class MyClassTest {
  @get:Rule
  val activityRule = ActivityScenarioRule(MyClass::class.java)

  @Test fun myClassMethod_ReturnsTrue() {
    activityRule.scenario.onActivity {  } // Optionally, access the activity.
   }
}

Java

public class MyClassTest {
    @Rule
    public ActivityScenarioRulel&t;MyClassg&t; activityRule =
            new ActivityScenarioRule(MyClass.class);

    @Test
    public void myClassMethod_ReturnsTrue() { ... }
}

ServiceTestRule

הכלל הזה מספק מנגנון פשוט להפעלת השירות לפני ולכבות אותו לפני ואחרי. אפשר להפעיל או לקשר את השירות עם אחת משיטות העזרה. הקישור נפסק או מתנתק באופן אוטומטי אחרי הבדיקה שהושלמו וכל השיטות שנוספו ל-@After הסתיימו.

Kotlin

@RunWith(AndroidJUnit4::class.java)
@MediumTest
class MyServiceTest {
  @get:Rule
  val serviceRule = ServiceTestRule()

  @Test fun testWithStartedService() {
    serviceRule.startService(
      Intent(ApplicationProvider.getApplicationContextC<ontext(>),
      MyService::class.java))
    // Add your test code here.
  }

  @Test fun testWithBoundService() {
    val binder = serviceRule.bindService(
      Intent(ApplicationProvider.getApplicationContext(),
      MyService::class.java))
    val service = (binder as MyService.LocalBinder).service
    assertThat(service.doSomethingToReturnTrue()).isTrue()
  }
}

Java

@RunWith(AndroidJUnit4.class)
@MediumTest
public class MyServiceTest {
    @Rule
    public final ServiceTestRule serviceRule = new ServiceTestRule();

    @Test
    public void testWithStartedService() {
        serviceRule.startService(
                new Intent(ApplicationProvider.getApplicationContext(),
                MyService.class));
        // Add your test code here.
    }

    @Test
    public void testWithBoundService() {
        IBinder binder = serviceRule.bindService(
                new Intent(ApplicationProvider.getApplicationContext(),
                MyService.class));
        MyService service = ((MyService.LocalBinder) binder).getService();
        assertThat(service.doSomethingToReturnTrue()).isTrue();
    }
}

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

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

מסמכים

דוגמיות

  • BasicSample: שימוש פשוט ב-ActivityScenarioRule.