package cn.itcast.myjunit;
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 cn.itcast.myjunit;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;
public class MyJunit {
/**
* @param args
* JUnit4 测试类执行方法:先获取类名,查找注解,反射执行测试类的方法
*/
public static void main(String[] args) {
System.err.println("please input a class name:");
Scanner sc = new Scanner(System.in);
String clsName = sc.nextLine();
try {
Object o = Class.forName(clsName).newInstance();
Method[] ms = o.getClass().getDeclaredMethods();
/*
* for(Method m : ms)
*/
for(int i=0;i<ms.length;i++) {
Method m = ms[i];
if(m.isAnnotationPresent(MyTest.class)) {
System.err.println("测试类"+o.getClass().getName()+"中的 "+m.getName()+"()方法 has annotation");
m.invoke(o, null);
}
}
System.err.println("done...............");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
package cn.itcast.myjunit;
public class HelloJunit {
@MyTest
public void test() {
System.err.println("my junit............");
}
}
直接运行MyJunit, 根据提示输入:cn.itcast.myjunit.HelloJunit