一、背景
在做自動(dòng)化測(cè)試中捍掺,經(jīng)常會(huì)出現(xiàn)一些由于各種因素引起的假性失敗(非bug)撼短,例如:頁(yè)面未加載出來、打開app失敗等現(xiàn)象挺勿。每次檢查測(cè)試結(jié)果阔加,需要花一些時(shí)間去鑒別是否為bug,采用的方法是再運(yùn)行一遍满钟,于是:是否可以在case執(zhí)行失敗時(shí)自動(dòng)rerun胜榔?
二、實(shí)現(xiàn)Rule
Junit4 提供了一些高級(jí)特性湃番,如@Rule夭织,框架自帶了一些Rule,也可以自己定義吠撮。以下自定義一個(gè)Rule尊惰,實(shí)現(xiàn)失敗重跑機(jī)制:
//使用自定義Rule
@Rule
public RetryRule retryRule = new RetryRule(2);
//實(shí)現(xiàn)TestRule接口
public class RetryRule implements TestRule {
private int retryCount;
public RetryRule(int retryCount) {
this.retryCount = retryCount;
}
public void setRetryCount(int retryCount) {
this.retryCount = retryCount;
}
public Statement apply(Statement base, Description description) {
return statement(base, description);
}
private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;
// implement retry logic here
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
HFLog.logMessage("-----------RetryRunner-----------: Test case success, " + (i + 1));
return;
} catch (Throwable t) {
caughtThrowable = t;
HFLog.logMessage("-----------RetryRunner-----------: Test case failed, " + (i + 1) + ", " + getExceptionMsg(caughtThrowable));
}
}
throw caughtThrowable;
}
};
}
三、參考資料:
https://segmentfault.com/a/1190000005923632
https://tonydeng.github.io/2016/05/11/junit-more-feature/
http://haibin369.iteye.com/blog/2088541