Junit Framework -TestRule,自动化测试中如何再次运行失败的测试用例

有时由于服务器,浏览器等问题,会导致自动化测试用例运行失败,此处通过案例讲解如何使用Junit框架中的TestRule来实现重复运行失败的测试用例。

首先定义一个类并让它实现TestRule,代码如下:

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement; public class RetryRule implements TestRule{
private final int retryCount;
//构造方法
public RetryRule(int retryCount){
this.retryCount=retryCount;
}
@Override
public Statement apply(Statement base, Description description) {
return statement(base,description);
}
private Statement statement(Statement base, 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 (final Throwable t) {
caughtThrowable=t;
System .err .println(description.getDisplayName()+":run"+(i+1)+"failed.");
}
}
System.err.println(description.getDisplayName()+":giving up after"+retryCount+"failure.");
throw caughtThrowable;
}
};
} }

  之后创建一个测试类,该类中选择打开https://www.baidu.com网站,测试网页标题中是否含有123。

import static org.junit.Assert.assertTrue;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class RetryRuleTest { static WebDriver driver;
private final String URL="https://meitaichina.alpha.tmogroup.asia/"; @BeforeClass
public static void setUpBeforeClass() throws Exception {
driver=new ChromeDriver();
}
@Rule
public RetryRule retryRule=new RetryRule(3); @Test
public void test() {
driver.get("https://www.baidu.com");
assertTrue("faile",driver.getTitle().toString().contains("123"));
} @AfterClass
public static void tearDownAfterClass() throws Exception {
driver.quit();
} }

  由于标题中并不存在123所以此时我们可以查看到运行结果,且确实运行了三次

Starting ChromeDriver 2.25.426924 (649f9b868f6783ec9de71c123212b908bf3b232e) on port 10920
Only local connections are allowed.
May 11, 2017 11:09:15 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
test(RetryRuleTest):run1failed.
test(RetryRuleTest):run2failed.
test(RetryRuleTest):run3failed.
test(RetryRuleTest):giving up after3failure.
上一篇:jquery ajax 事件执行顺序


下一篇:使用 apache ant 轻松实现文件压缩/解压缩(转)