總目錄:Espresso從開始到…
Espresso的官方文檔中提示,儘量使用Espresso提供的操作動作,來控制view,而且Espresso也確實提供了比較全面ViewAction
。
與Matcher
類似,所有的操作動作都是實現了interface ViewAction
。
public interface ViewAction {
/**
* 在 perform 使用時提及過,view 執行特定的操作需要滿足特定的條件
* 這裏是針對當前 ViewAction 對 view 設置的限制條件
*/
public Matcher<View> getConstraints();
/**
* 對當前的 view action 提供描述
*/
public String getDescription();
/**
* 對指定的 view 進行操作
*/
public void perform(UiController uiController, View view);
}
如果你看過前面的onView()&onData()這裏應該就很容易明白這裏所對應的操作,這裏簡單的總結一下ViewAction
的使用過程:
- 使用初始化信息拿到目標view準備開始進行操作(perform()和check()是整體的驅動器)
- 檢查一下目標view能否勝任當前的操作
getConstraints()
- 生成關於
ViewAction
的描述,用於之後和其他描述一起打印日誌 - 正式開始在目標 view 上進行
ViewAction
操作
自定義ViewAction
在瞭解一個大概流程之後再來看自定義ViewAction
並沒有什麼難度,這裏一起看一個栗子
//獲取指定view的文本內容
String tv = getText(withId(R.id.xxx));
public String getText(final Matcher<View> matcher) {
final String[] text = {null};
onView(matcher)
.perform(new ViewAction() {
//識別所操作的對象類型
@Override
public Matcher<View> getConstraints() {
return isAssignableFrom(TextView.class);
}
//視圖操作的一個描述
@Override
public String getDescription() {
return "getting text from a TextView";
}
//實際的一個操作,在之類我們就可以獲取到操作的對象了。
@Override
public void perform(UiController uiController, View view) {
TextView textView = (TextView)view;
text[0] = textView.getText().toString();
}
});
return text[0];
}
因爲常規的view的操作已經足夠使用了,這裏就借用於ViewAction
的特性,來獲取一些相關的屬性信息,使用一個數組(引用)將view中的屬性獲取出來,同樣的方法也可以將view
獲取出來
ViewActions
與Matcher
相同 Espresso 爲 使用者提供了大量的 ViewAction
供測試使用:
函數名 | 功能 |
---|---|
addGlobalAssertion() | 設置全局斷言 |
actionWithAssertions() | 包裝 action ,執行前必須滿足所有全局斷言 |
removeGlobalAssertion() | 刪除全局斷言 |
clearGlobalAssertions() | 清空全局斷言 |
clearText() | 清空文本 |
click() | 單擊 |
click(ViewAction rollbackAction() | 單擊(防止誤判爲長按) |
closeSoftKeyboard() | 關閉軟鍵盤 |
doubleClick() | 雙擊 |
longClick() | 長按 |
openLink() | 打開連接(TextView) |
openLinkWithText() | 打開連接(Text) |
openLinkWithUri() | 打開連接(Uri) |
pressBack() | 返回鍵 |
pressImeActionButton() | |
pressKey() | 根據Key模擬按鍵 |
pressMenuKey() | 實體鍵盤菜單鍵 |
replaceText() | 替換文本 |
scrollTo() | 滑動到 |
swipeDown() | 下滑 |
swipeLeft() | 左滑 |
swipeRight() | 右滑 |
swipeUp() | 上滑 |
typeText() | 獲得焦點並注入文本(模擬按鍵單個輸入) |
typeTextIntoFocusedView() | 在已獲得焦點的View上注入文本(模擬按鍵單個輸入) |