關於 Junit 的rule 自定義規則開發

關於Rule

查看Junit源碼,可看到 關於Rule的實現,有
org.junit.rules.TestRule 接口和 org.junit.rules.MethodRule 接口

TestRule

其中 TestRule主要針對一個測試類中的
1.org.junit.Before
2.org.junit.After
3.org.junit.BeforeClass
4.org.junit.AfterClass的相關處理

MethodRule

主要針對測試類的方法進行處理,本篇文章將重點說明這點,它可以支持 APP自動化/或者UI 自動化 等異常或正常執行的數據處理。提高整體代碼的簡潔及可讀性

實例

本篇文章我們的目標是實現,針對Junit測試執行出現的異常,打印出 對應的類名稱及方法名稱

實現

package com.finger.test.rule;

import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

/**
 * Created by 飛狐 on 2018/2/11.
 */
public class FailedRule implements MethodRule {

    private final String name;

    public FailedRule(String name){
        this.name = name;
    }


    public Statement apply(final Statement base, FrameworkMethod method, Object target){
        //類名稱
        final String className = target.getClass().getName();

        //執行方法名字
        final String methodName = method.getName();

        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    base.evaluate();
                    System.out.println("執行正常,自定義規則執行通過!!");
                }catch (Throwable throwable){
                    StringBuffer stringBuffer = new StringBuffer();

                    stringBuffer.append(name);
                    stringBuffer.append("執行失敗,失敗信息如下:");

                    stringBuffer.append("類名稱:" + className);
                    stringBuffer.append("方法名稱: " + methodName);

                    System.out.println(stringBuffer.toString());

                }
            }
        };

    }

}

測試類

package com.finger.test.temp;

import com.finger.test.rule.FailedRule;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;

/**
 * Junit Rule實現
 * Created by 飛狐 on 2018/2/11.
 */
public class RuleTest extends BaseTest{

    @Rule
    public FailedRule failedRule = new FailedRule("飛狐");

    /**
     * 測試一把哦
     */
    @Test
    public void test1(){
        Assert.assertTrue("這個結果應該是true",false);
    }

    /**
     * 測試一把哦
     */
    @Test
    public void test2(){
        Assert.assertTrue("這個結果應該是true",true);
    }

}

執行結果

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章