2015-12-03 2 views
15

Я пытаюсь проверить текст ActionPage с помощью Espresso. Тем не менее, когда я запускаю средство просмотра Ui Automation, я вижу, что ActionPage отображается как представление вместо ActionView и не имеет TextView.Android Espresso Ui Test проверяет текст ярлыка ActionPage

Я попытался проверить текст ActionLabel, как это, но это не работает:

onView(withClassName(equalToIgnoringCase("android.support.wearable.view.ActionLabel"))).check(matches(withText("MyText"))); 

У меня есть идентификатор для моей ActionPage, так что я могу найти его с onView(withId(R.id.actionPage)), но я не знаю, как получить доступ к своим детям чтобы получить текст ActionLabel. Я пытался писать пользовательский Искатель, но это также не работает:

onView(withId(R.id.actionPage)).check(matches(withChildText("MyText"))); 

static Matcher<View> withChildText(final String string) { 
     return new BoundedMatcher<View, View>(View.class) { 
      @Override 
      public boolean matchesSafely(View view) { 
       ViewGroup viewGroup = ((ViewGroup) view); 
       //return (((TextView) actionLabel).getText()).equals(string); 
       for(int i = 0; i < view.getChildCount(); i++){ 
        View child = view.getChildAt(i); 
        if (child instanceof TextView) { 
         return ((TextView) child).getText().toString().equals(string); 
        } 
       } 
       return false; 
      } 

      @Override 
      public void describeTo(Description description) { 
       description.appendText("with child text: " + string); 
      } 
     }; 
    } 

Может кто-то пожалуйста, помогите мне, то ActionLabel, кажется, не иметь идентификатор сам по себе и его не в TextView ... Как я могу проверить текст внутри?

+------>FrameLayout{id=-1, visibility=VISIBLE, width=320, height=320, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1} 
| 
+------->ActionPage{id=2131689620, res-name=actionPage, visibility=VISIBLE, width=320, height=320, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2} 
| 
+-------->ActionLabel{id=-1, visibility=VISIBLE, width=285, height=111, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=17.0, y=209.0} 
| 
+-------->CircularButton{id=-1, visibility=VISIBLE, width=144, height=144, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=88.0, y=65.0} 

enter image description here

+0

Можно ли добавить программное описание содержимого или идентификатор к хотя бы одному из этих макетов? Было бы намного легче поймать – piotrek1543

ответ

6

Вы можете использовать withParent с allOf:

onView(
    allOf(
     withParent(withId(R.id.actionPage)), 
     isAssignableFrom(ActionLabel.class))) 
    .check(matches(withActionLabel(is("MyText")))); 

К сожалению ActionLabel не раскрывает его текст через getText(), поэтому вместо стандартного withText() согласовани, вы должны написать пользовательский один с использованием отражения:

private static Matcher<Object> withActionLabel(
    final Matcher<CharSequence> textMatcher) { 
    return new BoundedMatcher<Object, ActionLabel>(ActionLabel.class) { 
    @Override public boolean matchesSafely(ActionLabel label) { 
     try { 
     java.lang.reflect.Field f = label.getClass().getDeclaredField("mText"); 
     f.setAccessible(true); 
     CharSequence text = (CharSequence) f.get(label); 
     return textMatcher.matches(text); 
     } catch (NoSuchFieldException e) { 
     return false; 
     } catch (IllegalAccessException e) { 
     return false; 
     } 
    } 
    @Override public void describeTo(Description description) { 
     description.appendText("with action label: "); 
     textMatcher.describeTo(description); 
    } 
    }; 
} 

Подробнее: http://blog.sqisland.com/2015/05/espresso-match-toolbar-title.html

Пожалуйста, сообщите об ошибке, чтобы запросить Google добавить публичный метод ActionLabel.getText() так что вы можете проверить это без отражения.

+0

Спасибо! Проблема заключается в том, что 'ActionLabel' не присваивается' TextView', а 'ActionLabel' не имеет открытого метода' getText() '. – AlexIIP

+0

Является ли 'ActionLabel' вашим пользовательским видом? Если это так, вы можете добавить 'getText()' метод и написать пользовательский матчи, используя это. См. Ссылку в блоге для образца пользовательского совпадения. – chiuki

+0

Его нет, его класс андроида. http://developer.android.com/reference/android/support/wearable/view/ActionPage.html – AlexIIP

Смежные вопросы