Espresso: return boolean se a visão existe

Estou tentando viewificair se uma exibição é exibida com o Espresso. Aqui está um pseudo código paira mostrair o que estou tentando:

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

Mas meu problema é .check(doesNotExist()) não retorna boolean. É apenas uma afirmação. Com UiAutomator eu consegui apenas fazer algo assim:

  • java Lang UnsupportedClassVersion Error no Xamairin Studio
  • Usando $ {applicationId} no manifesto da biblioteca
  • Android PagerAdapter não informa a position correta se clicair no item anterior
  • Emulair o file de hosts no Android não rooteado
  • Tentando criair a resposta rápida do WhatsApps paira telefones pré N
  • ActionBairSherlock spinner não selecionável ins ActionBair - tema relacionado
  •   if (UiAutomator.getbyId(SomeId).exists){ ..... } 

    Eu achei isto; viewifique a linha 46 . Ainda não consigo descobrir como usá-lo.

  • Como vinculair um CursorAdapter a um ExpandableListView?
  • Android - Transmissão de vídeo pelo server HTTPS local: certificate SSL rejeitado
  • Como exibir meu layout de rolagem acima do keyboard?
  • Erro: Erro ao recuperair o pai pelo item: Nenhum recurso encontrado que corresponde ao nome dado 'Widget.AppCompat.ActionButton'
  • PhoneGap - performance ruim compairado ao browser no Android
  • Por que eu tenho "Configurando airplane_mode_on mudou de android.provider.Settings.System " paira o logcat quando meu aplicativo não tem nada a view com isso?
  • 5 Solutions collect form web for “Espresso: return boolean se a visão existe”

    Precisamos dessa funcionalidade e acabei por implementá-la abaixo:

    https://github.com/maircosdiez/espresso_clone

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

    Espero que seja útil paira você.

    A lógica condicional em testes não é desejável . Com isso em mente, a API da Espresso foi projetada paira guiair o autor do teste longe dele (sendo explícito com ações de teste e asserções).

    Dito isto, você ainda pode alcançair o acima, implementando seu próprio ViewAction e capturando a viewificação isDisplayed (dentro do método de execução) em um AtomicBoolean.

    Outra opção less elegante – pegue a exception que é jogada pela viewificação crashda:

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

    Você também viewifica com o código abaixo. Se a exibição for exibida, ela clicairá em outro lugair, passairá.

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

    Eu acho que imitair o UIAutomator você pode fazer isso:
    ( Embora, eu sugiro repensair sua abordagem paira não ter condições. )

     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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } } 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } } 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } } 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } } 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } }); 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } retornair viewdadeiro; 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } retornair viewdadeiro; 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } retornair falso; 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } retornair falso; 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } } 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() { @Oviewride public Matcher<View> getConstraints() { return any(View.class); } @Oviewride public String getDescription() { return "check for existence"; } @Oviewride 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; } } 

    Também exists sem ramificação pode ser implementado de forma muito simples:

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

    Embora na maioria das vezes vale a pena viewificair as matches(isDisplayed()) qualquer maneira.

    Com base na resposta de Dhiren Mudgil, acabei por escreview o seguinte método:

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

    Estou usando isso paira ajudair a determinair qual exibição em um ViewFlipper é exibida atualmente.

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.