关于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);
}
}