注解学习:实现简单的junit的@test注解

来源:互联网 发布:python 元组添加元素 编辑:程序博客网 时间:2024/06/07 07:51

编写注解:

import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)  //运行时保留注解@Target(ElementType.METHOD)   //只在方法声明中合法public @interface Test2 {}
编写使用注解的类,其中m3,m7抛出异常,m1,m5不抛出异常,但m5为实例方法,不存在注解的有效使用:

public class Sample {@Test2public static void m1(){};public static void m2(){};
@Test2public static void m3(){throw new RuntimeException("Boom");};public static void m4(){};@Test2public  void m5(){};public static void m6(){};@Test2public static void m7(){throw new RuntimeException("crash");};public static void m8(){};}

编写测试类,利用反射运行注解类中所有还有test2注解的方法:

import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class RunTest {public static void main(String[] args) throws Exception {int tests=0;int passed=0;Class testClass=Class.forName(Sample.class.getName());for(Method m:testClass.getDeclaredMethods()){if(m.isAnnotationPresent(Test2.class)){tests++;try{m.invoke(null);passed++;}catch(InvocationTargetException e){Throwable exc=e.getCause();System.out.println(m+"failed"+exc);}catch (Exception e) {System.out.println("INVALID @TEST2 :" +m);}}}System.out.println("tests:"+tests);System.out.println("passed:"+passed);}}
运行后的结果为:

public static void springMVC.Sample.m3()failedjava.lang.RuntimeException: BoomINVALID @TEST2 :public void springMVC.Sample.m5()public static void springMVC.Sample.m7()failedjava.lang.RuntimeException: crashtests:4passed:1




0 0
原创粉丝点击