介绍
本文介绍如何对JUnit进行扩展,从而更好地做单元测试。
下面采用的Maven依赖版本为:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
先给出一个最终的例子:
/**
* @author suren
* @date 2017年6月30日 下午5:13:14
*/
public class SwaggerParseTest
{
@Rule
public ReportRule reportRule = new ReportRule();
@Test
@Skip
public void justForTest()
{
System.out.println("just for test");
}
}
可以看到,这里多了两个注解(@Rule、@Skip)和一个属性ReportRule,@Rule是JUnit提供的,@SKip是我们自定义的注解类
/**
* @author suren
* @date 2017年7月1日 上午9:26:10
*/
@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface Skip
{
}
@Skip是用来标注要跳过的方法,主要的实现逻辑如下,通过JUnit的MethodRule接口来实现:
/**
* @author suren
* @date 2017年7月1日 上午9:21:23
*/
public class ReportRule implements MethodRule
{
@Override
public Statement apply(Statement base, FrameworkMethod method,
Object target)
{
if(method.getAnnotation(Skip.class) != null)
{
return new Statement(){
@Override
public void eval() throws Throwable
{
}
};
}
return base;
}
}
最后,要注意的是:Report类必须要实现接口MethodRule,而申明的属性必须要是public、非静态(static)的。
参考
本文为原创,如果您当前访问的域名不是surenpi.com,请访问“素人派”。
查看原文:http://surenpi.com/2017/07/01/junit_extention/