Espresso

Espresso-Intents to rozszerzenie Espresso, które umożliwia krótkie zamierzenia zamiarów wysyłane przez aplikacji w trakcie testowania. Jak Mockito, ale w przypadku intencji Androida.

Jeśli Twoja aplikacja przekazuje funkcje innym aplikacjom lub platformie, możesz użyć Espresso-intencje, które pozwalają skupić się na logice Twojej aplikacji, zakładając, że inne aplikacje lub platforma działa poprawnie. Dzięki Espresso-Intents i weryfikować intencje wychodzące, a nawet podać krótkie odpowiedzi zamiast odpowiedzi na rzeczywiste intencje.

Uwzględnij w projekcie intencje Espresso

W pliku app/build.gradle aplikacji dodaj ten wiersz dependencies:

androidTestImplementation 'androidx.test.espresso:espresso-intents:3.6.1'
androidTestImplementation('androidx.test.espresso:espresso-intents:3.6.1')

Espresso-Intents jest zgodne tylko z Espresso 2.1 i nowszym oraz 0.3+ Biblioteki testowe dla Androida, więc pamiętaj o zaktualizowaniu tych wierszy również:

androidTestImplementation 'androidx.test:runner:1.6.1'
androidTestImplementation
'androidx.test:rules:1.6.1'
androidTestImplementation
'androidx.test.espresso:espresso-core:3.6.1'
androidTestImplementation('androidx.test:runner:1.6.1')
androidTestImplementation
('androidx.test:rules:1.6.1')
androidTestImplementation
('androidx.test.espresso:espresso-core:3.6.1')

Pisz reguły testowe

Zanim napiszesz test Espresso-Intents, skonfiguruj IntentsTestRule. To jest rozszerzenie klasy ActivityTestRule i ułatwia korzystanie Interfejsy API Espresso Intents w funkcjonalnych testach interfejsu użytkownika. Inicjowanie obiektu IntentsTestRule Intencje Espresso przed każdym testem z adnotacjami @Test i wersjami Intencje Espresso po każdym teście.

Oto przykładowy fragment kodu (IntentsTestRule):

KotlinJava
@get:Rule
val intentsTestRule = IntentsTestRule(MyActivity::class.java)
@Rule
public IntentsTestRule<MyActivity> intentsTestRule =
   
new IntentsTestRule<>(MyActivity.class);

Dopasowanie

Espresso-Intents umożliwia przechwytywanie intencji wychodzących na podstawie określonych kryteriów, zdefiniowanych za pomocą funkcji Hamcrest Matchers. Hamcrest umożliwia:

  • Użyj istniejącego dopasowywania intencji: najprostsza opcja, która powinna prawie zawsze być dostępna. być preferowane.
  • Wdróż dopasowywanie intencji: najbardziej elastyczna opcja. Więcej informacji: dostępne w sekcji „Pisanie dopasowań niestandardowych”. w ciągu Samouczek dotyczący Hamcrest.

Espresso-Intents oferuje intended() oraz metody intending() do walidacji intencji lub skrócenie czasu. Obie biorą obiekt Hamcrest Matcher<Intent> jako .

Ten fragment kodu pokazuje weryfikację intencji z dotychczasową intencją dopasowania pasujące do intencji wychodzącej uruchamiającej przeglądarkę:

KotlinJava
assertThat(intent).hasAction(Intent.ACTION_VIEW)
assertThat
(intent).categories().containsExactly(Intent.CATEGORY_BROWSABLE)
assertThat
(intent).hasData(Uri.parse("www.google.com"))
assertThat
(intent).extras().containsKey("key1")
assertThat
(intent).extras().string("key1").isEqualTo("value1")
assertThat
(intent).extras().containsKey("key2")
assertThat
(intent).extras().string("key2").isEqualTo("value2")
assertThat(intent).hasAction(Intent.ACTION_VIEW);
assertThat
(intent).categories().containsExactly(Intent.CATEGORY_BROWSABLE);
assertThat
(intent).hasData(Uri.parse("www.google.com"));
assertThat
(intent).extras().containsKey("key1");
assertThat
(intent).extras().string("key1").isEqualTo("value1");
assertThat
(intent).extras().containsKey("key2");
assertThat
(intent).extras().string("key2").isEqualTo("value2");

Zweryfikuj intencje

Espresso-Intents rejestruje wszystkie intencje, które próbują uruchomić aplikacji w trakcie testowania. Użycie metody intended(), która jest podobna do Mockito.verify(), możesz twierdzić, że dana intencja została zauważona. Pamiętaj jednak: Espresso-Intents nie wyklucza odpowiedzi na intencje, chyba że specjalnie skonfigurujesz w tym celu.

Poniższy fragment kodu to przykładowy test, który weryfikuje, ale nie stosuje częściowej konfiguracji w odpowiedzi na wiadomości, intencję wychodzącą generującą uruchamiający zewnętrzny „telefon” aktywność:

KotlinJava
@Test fun validateIntentSentToPackage() {
   
// User action that results in an external "phone" activity being launched.
    user
.clickOnView(system.getView(R.id.callButton))

   
// Using a canned RecordedIntentMatcher to validate that an intent resolving
   
// to the "phone" activity has been sent.
    intended
(toPackage("com.android.phone"))
}
@Test
public void validateIntentSentToPackage() {
   
// User action that results in an external "phone" activity being launched.
    user
.clickOnView(system.getView(R.id.callButton));

   
// Using a canned RecordedIntentMatcher to validate that an intent resolving
   
// to the "phone" activity has been sent.
    intended
(toPackage("com.android.phone"));
}

Stukanie

Przy użyciu metody intending(), podobnej do metody Mockito.when(), można a w przypadku działań uruchomionych z użyciem tego fragmentu startActivityForResult() Jest to szczególnie przydatne w przypadku czynności wykonywanych na zewnątrz ponieważ nie można manipulować interfejsem użytkownika w ramach działań zewnętrznych ani kontrolować pole ActivityResult zwrócone do testowanej aktywności.

Poniższe fragmenty kodu zawierają przykład activityResult_DisplaysContactsPhoneNumber(), który sprawdza, czy użytkownik uruchamia „kontakt” aktywność w testowanej aplikacji, kontaktowy numer telefonu wyświetlany jest numer:

  1. Utwórz wynik, który będzie zwracany po uruchomieniu określonego działania. przykładowy test przechwytuje wszystkie intencje wysłane do „kontaktów” i kończy odpowiedzi z prawidłowym elementem ActivityResult, przy użyciu kodu wyniku RESULT_OK

    KotlinJava
    val resultData = Intent()
    val phoneNumber = "123-345-6789"
    resultData
    .putExtra("phone", phoneNumber)
    val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)
    Intent resultData = new Intent();
    String phoneNumber = "123-345-6789";
    resultData
    .putExtra("phone", phoneNumber);
    ActivityResult result =
       
    new ActivityResult(Activity.RESULT_OK, resultData);
  2. Poproś Espresso o podanie obiektu z wycinkiem w odpowiedzi na wszystkie wywołania „kontaktów” intencja:

    KotlinJava
    intending(toPackage("com.android.contacts")).respondWith(result)
    intending(toPackage("com.android.contacts")).respondWith(result);
  3. Sprawdź, czy działanie użyte do uruchomienia działania generuje oczekiwaną z kropką. W takim przypadku przykładowy test sprawdza, czy numer telefonu „123-345-6789” jest zwracany i wyświetlane, gdy „aktywność kontaktów” uruchomiono:

    KotlinJava
    onView(withId(R.id.pickButton)).perform(click())
    onView
    (withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)))
    onView(withId(R.id.pickButton)).perform(click());
    onView
    (withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));

Oto pełny test funkcji activityResult_DisplaysContactsPhoneNumber():

KotlinJava
@Test fun activityResult_DisplaysContactsPhoneNumber() {
   
// Build the result to return when the activity is launched.
   
val resultData = Intent()
   
val phoneNumber = "123-345-6789"
    resultData
.putExtra("phone", phoneNumber)
   
val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)

   
// Set up result stubbing when an intent sent to "contacts" is seen.
    intending
(toPackage("com.android.contacts")).respondWith(result)

   
// User action that results in "contacts" activity being launched.
   
// Launching activity expects phoneNumber to be returned and displayed.
    onView
(withId(R.id.pickButton)).perform(click())

   
// Assert that the data we set up above is shown.
    onView
(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)))
}
@Test
public void activityResult_DisplaysContactsPhoneNumber() {
   
// Build the result to return when the activity is launched.
   
Intent resultData = new Intent();
   
String phoneNumber = "123-345-6789";
    resultData
.putExtra("phone", phoneNumber);
   
ActivityResult result =
       
new ActivityResult(Activity.RESULT_OK, resultData);

   
// Set up result stubbing when an intent sent to "contacts" is seen.
    intending
(toPackage("com.android.contacts")).respondWith(result);

   
// User action that results in "contacts" activity being launched.
   
// Launching activity expects phoneNumber to be returned and displayed.
    onView
(withId(R.id.pickButton)).perform(click());

   
// Assert that the data we set up above is shown.
    onView
(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));
}

Dodatkowe materiały

Jeśli chcesz dowiedzieć się więcej o używaniu Espresso-Intents w testach Androida, skontaktuj się z zespołem pomocy. poniższe zasoby.

Próbki