6.2 Demo 模擬單元測試
阿新 • • 發佈:2018-12-06
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); } } } } }