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.

 

转载于:https://www.cnblogs.com/woniu123/p/6837472.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值