-
介绍
本文介绍如何对JUnit进行扩展,从而更好地做单元测试。
下面采用的Maven依赖版本为:
1 2 3 4 5 |
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> </dependency> |
先给出一个最终的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/** * @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是我们自定义的注解类
1 2 3 4 5 6 7 8 9 10 |
/** * @author suren * @date 2017年7月1日 上午9:26:10 */ @Documented @Retention(RUNTIME) @Target(METHOD) public @interface Skip { } |
@Skip是用来标注要跳过的方法,主要的实现逻辑如下,通过JUnit的MethodRule接口来实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/** * @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 evaluate() throws Throwable { } }; } return base; } } |
最后,要注意的是:Report类必须要实现接口MethodRule,而申明的属性必须要是public、非静态(static)的。
-
参考
本文为原创,如果您当前访问的域名不是surenpi.com,请访问“素人派”。