unit tutorial test support studio library androidtestimplementation java android android-testing android-espresso

java - tutorial - Espresso: return boolean si existe la vista



test ui android (5)

Estoy tratando de verificar si una vista se muestra con Espresso. Aquí hay un pseudo código para mostrar lo que estoy intentando:

if (!Espresso.onView(withId(R.id.someID)).check(doesNotExist()){ // then do something } else { // do nothing, or what have you }

Pero mi problema es .check(doesNotExist()) no devuelve boolean. Es solo una afirmación. Con UiAutomator, pude hacer algo así:

if (UiAutomator.getbyId(SomeId).exists()){ ..... }


Creo que para imitar a UIAutomator puedes hacer esto:
( Sin embargo, sugiero repensar su enfoque para no tener condiciones ) .

ViewInteraction view = onView(withBlah(...)); // supports .inRoot(...) as well if (exists(view)) { view.perform(...); } @CheckResult public static boolean exists(ViewInteraction interaction) { try { interaction.perform(new ViewAction() { @Override public Matcher<View> getConstraints() { return any(View.class); } @Override public String getDescription() { return "check for existence"; } @Override public void perform(UiController uiController, View view) { // no op, if this is run, then the execution will continue after .perform(...) } }); return true; } catch (AmbiguousViewMatcherException ex) { // if there''s any interaction later with the same matcher, that''ll fail anyway return true; // we found more than one } catch (NoMatchingViewException ex) { return false; } catch (NoMatchingRootException ex) { // optional depending on what you think "exists" means return false; } }

También exists sin ramificación se puede implementar realmente simple:

onView(withBlah()).check(exists()); // the opposite of doesNotExist() public static ViewAssertion exists() { return matches(anything()); }

Aunque la mayoría de las veces vale la pena buscar matches(isDisplayed()) todos modos.


En base a la respuesta de Dhiren Mudgil, terminé escribiendo el siguiente método:

public static boolean viewIsDisplayed(int viewId) { final boolean[] isDisplayed = {true}; onView(withId(viewId)).withFailureHandler(new FailureHandler() { @Override public void handle(Throwable error, Matcher<View> viewMatcher) { isDisplayed[0] = false; } }).check(matches(isDisplayed())); return isDisplayed[0]; }

Estoy usando esto para ayudar a determinar qué Vista en un ViewFlipper se muestra actualmente.


La lógica condicional en las pruebas es undesirable . Teniendo esto en cuenta, la API de Espresso se diseñó para alejar al autor de la prueba (al ser explícito con las acciones de prueba y las afirmaciones).

Una vez dicho esto, puede lograr lo anterior al implementar su propia ViewAction y capturar la comprobación isDisplayed (dentro del método de ejecución) en un AtomicBoolean.

Otra opción menos elegante: captar la excepción que arroja el cheque fallido:

try { onView(withText("my button")).check(matches(isDisplayed())); //view is displayed logic } catch (NoMatchingViewException e) { //view not displayed logic }


Necesitamos esa funcionalidad y terminé implementándola a continuación:

https://github.com/marcosdiez/espresso_clone

if(onView(withText("click OK to Continue")).exists()){ doSomething(); } else { doSomethingElse(); }

Espero que sea útil para ti.


También verifica con el código siguiente. Si se muestra la vista, hará clic en "else" y pasará.

onView(withText("OK")).withFailureHandler(new FailureHandler() { @Override public void handle(Throwable error, Matcher<View> viewMatcher){ } }).check(matches(isDisplayed())).perform(customClick());