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

编写注解:

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 {
	
	
	@Test2
	public static void m1(){};
	public static void m2(){};
	@Test2
	public static void m3(){
		throw new RuntimeException("Boom");
	};
	public static void m4(){};
	@Test2
	public  void m5(){};
	public static void m6(){};
	@Test2
	public 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: Boom
INVALID @TEST2 :public void springMVC.Sample.m5()
public static void springMVC.Sample.m7()failedjava.lang.RuntimeException: crash
tests:4
passed:1




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值