6.2 Demo 模拟单元测试

package com.xiaowei.mytest;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

public @interface MyTest {

}
package com.xiaowei.mytest;

import org.junit.Test;

public class TestDemo {

	@Test
	public void show1(){
		System.out.println("我是show1");
		
	}
	
	@MyTest
	public void show2(){
		System.out.println("我是show2");		
	}
	
	@MyTest
	public void show3(){
		System.out.println("我是show3");		
	}	
}
package com.xiaowei.mytest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyTestParster {

	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
		
//		1.获取TestDemo的字节码对象
		Class clazz = TestDemo.class;
//		2.通过字节码对象获取所有的方法
		Method[] methods = clazz.getMethods();
//		3.对所有的方法进行遍历 
//		首先作非空判断
		if (methods != null) {
			for (Method method : methods) {
//				4.判断该方法是否使用了MyTest注解
				boolean annotationPresent = method.isAnnotationPresent(MyTest.class);
				if (annotationPresent) {
//					5.需要回顾下这句代码
					method.invoke(clazz.newInstance(), null);
				}
			}
		}	
	}		
}

猜你喜欢

转载自blog.csdn.net/qq_43629005/article/details/84835806