Junit4 @Rule方法--Rerun失败测试用例

2018-02-28  本文已影响0人  初心不忘J

一、背景
在做自动化测试中,经常会出现一些由于各种因素引起的假性失败(非bug),例如:页面未加载出来、打开app失败等现象。每次检查测试结果,需要花一些时间去鉴别是否为bug,采用的方法是再运行一遍,于是:是否可以在case执行失败时自动rerun?

二、实现Rule
Junit4 提供了一些高级特性,如@Rule,框架自带了一些Rule,也可以自己定义。以下自定义一个Rule,实现失败重跑机制:
//使用自定义Rule
@Rule
public RetryRule retryRule = new RetryRule(2);

//实现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

上一篇下一篇

猜你喜欢

热点阅读