2017-02-28 86 views
0

我想檢查使用/取消選中複選框在我的咖啡測試:如何專注於espresso中的頁面元素?

termsAndConditionsCheckbox.check(matches(isChecked())); 
termsAndConditionsCheckbox.perform(scrollTo()).perform(click()); 
termsAndConditionsCheckbox.check(matches(isNotChecked())); 

但得到錯誤:

Error performing 'scroll to' on view 
Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints: 
      (view has effective visibility=VISIBLE and is descendant of a: (is assignable from class: class android.widget.ScrollView or is assignable from class: class android.widget.HorizontalScrollView)) 
      Target view: "AppCompatCheckBox{id=2131689839, res-name=tnc_checkbox, visibility=VISIBLE, width=96, height=96, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-conn 

通過去除scrollTo,只用點擊(),但仍無法嘗試執行點擊。

+0

ScrollView是否是CheckBox? –

+0

不,但我嘗試了幾個選項,如scrollTo() –

+0

'scrollTo()'期望目標元素是'ScrollView'的子元素,所以如果你的視圖太大而不適合屏幕,你需要將其封裝在佈局XML中的'ScrollView'中。很快就會寫出完整的答案。 –

回答

1

您收到的錯誤消息指出,您的CheckBox必須都是VISIBLE以及ScrollViewHorizontalScrollView的孩子。您的CheckBox確實是VISIBLE,但不是ScrollView的子女。因此,如果你有一個佈局,如:

<ScrollView ...> 
    <LinearLayout ...> 
     <TextView android:id="@+id/lbl_license_text" ... /> 
     <CheckBox android:id="@+id/chk_accept" ... /> 
    </LinearLayout> 
</ScrollView> 

(顯然取代的...實例與android:

<LinearLayout ...> 
    <TextView android:id="@+id/lbl_license_text" ... /> 
    <CheckBox android:id="@+id/chk_accept" ... /> 
</LinearLayout> 

你需要用它ScrollView使視圖內可以在更小屏幕設備滾動該元素的屬性)

這將允許Espresso在運行測試時向下滾動到CheckBox

0

我能夠通過實現自定義ViewAction這一功能來解決這個問題(看到它在計算器的答案之一)

public static ViewAction setChecked(final boolean checked) { 
    return new ViewAction() { 
     @Override 
     public Matcher<View> getConstraints() { 
      return new Matcher<View>() { 
       @Override 
       public boolean matches(Object item) { 
        return isA(Checkable.class).matches(item); 
       } 

       @Override 
       public void describeMismatch(Object item, Description mismatchDescription) {} 

       @Override 
       public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {} 

       @Override 
       public void describeTo(Description description) {} 
      }; 
     } 

     @Override 
     public String getDescription() { 
      return null; 
     } 

     @Override 
     public void perform(UiController uiController, View view) { 
      Checkable checkableView = (Checkable) view; 
      checkableView.setChecked(checked); 
     } 
    }; 
} 

,然後調用:

termsAndConditionsCheckbox.perform(Helper.setChecked(false)); 

取消選中和傳球如果選中該複選框,則爲true。