建议的评论是根据这篇文章撰写的,并附有一些补充内容。
在这里,如果jUnit项目中的某些测试用例得到“失败”或“错误”的结果,则该测试用例将再次运行一次。在这里,我们总共设置了3个获得成功结果的机会。
所以,我们需要创建规则类和添加“@rule”通知到您的测试类。
如果不想为每个测试类使用相同的“ @Rule”通知,则可以将其添加到抽象SetProperty类(如果有)中并从中扩展。
规则类别:
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class RetryRule implements TestRule {
private int retryCount;
public RetryRule (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;
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
System.err.println(description.getDisplayName() + ": run " + (i + 1) + " failed.");
}
}
System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures.");
throw caughtThrowable;
}
};
}
}
测试类别:
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class RetryRuleTest {
static WebDriver driver;
final private String URL = "http://www.swtestacademy.com";
@BeforeClass
public static void setupTest(){
driver = new FirefoxDriver();
}
@Rule
public RetryRule retryRule = new RetryRule(3);
@Test
public void getURLExample() {
driver.get(URL);
assertThat(driver.getTitle(), is("WRONG TITLE"));
}
}