今天繼續(xù)分享幾個(gè)UiAutomator2.0中的小技巧,在移動(dòng)端自動(dòng)化測試中,有時(shí)候需要用到從黏貼板上獲取內(nèi)容,比如在界面上點(diǎn)了或觸發(fā)了復(fù)制操作,后續(xù)想把復(fù)制的內(nèi)容黏貼出來該如何操作?一般有2種方式:
- 第一種適合輸入框、文本框等輸入型控件,可以直接模擬鍵盤輸入Ctrl+V,這樣就把內(nèi)容黏貼到對(duì)應(yīng)控件了;
- 第二種我要獲取的內(nèi)容并不需要輸入到某個(gè)控件,僅僅是就想獲得之前復(fù)制的內(nèi)容,這時(shí)候就適合操作黏貼板來獲得復(fù)制的內(nèi)容了。
代碼很簡單,如下:
public static String getClipboardContent(){
Handler handler = new Handler(Looper.getMainLooper());
final StringBuffer data = new StringBuffer();
handler.postDelayed(new Runnable() {
@Override
public void run() {
ClipboardManager myClipboard = (ClipboardManager)mAppContext.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = myClipboard.getPrimaryClip();
if (clipData != null && clipData.getItemCount() > 0) {
// 從數(shù)據(jù)集中獲取(粘貼)第一條文本數(shù)據(jù)
CharSequence text = clipData.getItemAt(0).getText();
data.append(text.toString());
}
}
}, 500);
sleep(800);//Thread.sleep(800)的異常封裝而已
return data.toString();
}
需要特別說明的是:
- 在創(chuàng)建ClipboardManager 對(duì)象時(shí)需要傳入一個(gè)Context對(duì)象,這個(gè)context不能用測試的context,而必須用測試應(yīng)用的context,下面給出對(duì)應(yīng)的定義差異:
Context mContext = InstrumentationRegistry.getContext(); //當(dāng)前測試的Context
Context mAppContext = InstrumentationRegistry.getTargetContext(); //當(dāng)前測試應(yīng)用的Context
-
上面操作黏貼板的代碼不能直接放在主線程,不然會(huì)拋出下面的異常,所以需要自己去開個(gè)線程,將操作黏貼板的代碼放在新開的線程中即可。
對(duì)于黏貼板的復(fù)制操作,上面的都搞定了,那就灰常簡單了,至于要不要放到子線程里面,還木有嘗試過,有需要的童鞋可以嘗試一下。
ClipboardManager myClipboard = (ClipboardManager)mAppContext.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData myClip = ClipData.newPlainText("text", "your copy content");
myClipboard.setPrimaryClip(myClip);
原文來自下方公眾號(hào),轉(zhuǎn)載請聯(lián)系作者,并務(wù)必保留出處。
想第一時(shí)間看到更多原創(chuàng)技術(shù)好文和資料,請關(guān)注公眾號(hào):測試開發(fā)棧
