使用WaitForView提高控件點(diǎn)擊成功率
? ? 開發(fā)界面自動(dòng)化的代碼時(shí)顿膨,難以避免的一個(gè)問(wèn)題是锅锨,因某些原因?qū)е驴丶訒r(shí)顯示,而這時(shí)點(diǎn)擊控件或在控件中輸入文本時(shí)恋沃,就會(huì)導(dǎo)致失敗或異常必搞。
? ? 我們通常的做法是,在代碼前添加一個(gè)等待語(yǔ)句囊咏,在該等待之后恕洲,控件應(yīng)該能出現(xiàn)。如梅割,
solo.sleep(10000);//等待10秒
solo.clickOnView(view)霜第;
? ? 不過(guò),由于等待時(shí)間并不確定户辞,認(rèn)為較長(zhǎng)的等待時(shí)間泌类,也許還不夠長(zhǎng),仍然會(huì)有對(duì)應(yīng)控件尚未出現(xiàn)的情況底燎;而如果每個(gè)等待都設(shè)置較長(zhǎng)的等待時(shí)間刃榨,又會(huì)造成大量的時(shí)間浪費(fèi),導(dǎo)致自動(dòng)化運(yùn)行效率不高双仍。因而枢希,我們封裝時(shí),可考慮封裝成:
if(solo.waitForView(view)) {
solo.clickOnView(view);
}
? ? 上面的判斷朱沃,如果能夠找到對(duì)應(yīng)的view苞轿,則不用等待,立即返回true逗物;如果在默認(rèn)超時(shí)時(shí)間(20秒)前找到view搬卒,則也返回true;否則返回false敬察。通過(guò)這個(gè)判斷秀睛,可以比設(shè)置常量效率高很多,因?yàn)檫@既可以保證在較長(zhǎng)時(shí)間出現(xiàn)控件時(shí)莲祸,仍能找到控件蹂安,也能在立即出現(xiàn)控件后椭迎,不用等待即可進(jìn)行后續(xù)操作。
? ? 有時(shí)田盈,默認(rèn)的20秒可能不夠畜号,或者控件不在當(dāng)前界面,可以考慮封裝成
if(solo.waitForView(view)允瞧,timeout時(shí)間简软,true) {
solo.clickOnView(view);
}
這時(shí),超時(shí)時(shí)間就是timeout時(shí)間述暂,而不是默認(rèn)的了痹升。
Robotium提供的WaitFor方法
? ? 為了提高找到對(duì)應(yīng)界面控件的成功率,Robotium提供了很多WaitFor方法畦韭,這些方法如包括waitForText疼蛾、waitForView、waitForWebElement艺配、waitForCondition察郁、waitForActivity、waitForLogMessage转唉、waitForFragmentById皮钠、waitForDialogToClose、waitForDialogToOpen等赠法。其中麦轰,各種不同參數(shù)的WaitForView方法如下,其他方法類似期虾,但參數(shù)種類不如WaitForView方法多:
boolean?waitForView(Class?viewClass)
? ? ?Waits for a View? matching the specified class.
boolean?waitForView(Class?viewClass,? int?minimumNumberOfMatches, int?timeout)
boolean?waitForView(Class?viewClass,? int?minimumNumberOfMatches, int?timeout, boolean?scroll)
boolean?waitForView(int?id)
boolean?waitForView(int?id, int?minimumNumberOfMatches, int?timeout)
boolean?waitForView(int?id, int?minimumNumberOfMatches, int?timeout, boolean?scroll)
boolean?waitForView(Objecttag)
boolean?waitForView(Objecttag,? int?minimumNumberOfMatches, int?timeout)
boolean?waitForView(Objecttag,? int?minimumNumberOfMatches, int?timeout, boolean?scroll)
boolean?waitForView(android.view.View?view)
boolean?waitForView(android.view.View?view,int?timeout, boolean?scroll)
超時(shí)時(shí)間
? ? Robotium的默認(rèn)超時(shí)時(shí)間為20s原朝,這個(gè)時(shí)間也是可以改變的驯嘱,而且有最大超時(shí)和最小超時(shí)镶苞。最大超時(shí)就是應(yīng)用于我們前面提到的waitFor方法。
TimeOut類提供的方法如下:
static int?getLargeTimeout()
? ? ?Gets the default? timeout length of the waitFor methods.
static int ?getSmallTimeout()
? ? ?Gets the default? timeout length of the get, is, set, assert, enter, type and click methods.
static void ?setLargeTimeout(int?milliseconds)
? ? ?Sets the default? timeout length of the waitFor methods.
static void ?setSmallTimeout(int?milliseconds)
? ? ?Sets the default? timeout length of the get, is, set, assert, enter, type and click methods.
? ? 雖然Robotium本身提供的方法的穩(wěn)定性和成功率越來(lái)越高鞠评,但針對(duì)自己的產(chǎn)品茂蚓,我們可以使用Robotium提供的WaitFor方法和超時(shí)時(shí)間等,對(duì)不同的界面及控件類型剃幌,采用更好的實(shí)現(xiàn)策略聋涨;通過(guò)組合這些方法,進(jìn)行恰當(dāng)?shù)姆庋b负乡,可以即提高自動(dòng)化執(zhí)行的效率牍白,又能提高執(zhí)行的成功率,也提高代碼編寫的效率抖棘。感興趣的茂腥,可以自己也試下狸涌。