写一个自己的JUnit

import java.lang.reflect.Method;
import java.util.Scanner;


public class MyJUnit {

public static void main(String[] args) throws Exception {
System.out.println("请输入被测试类的完整类名:"); //
Scanner sc = new Scanner(System.in);
String clsName = sc.nextLine();

//类反射
Class c = Class.forName(clsName);
Object obj = c.newInstance();

//注解+类反射
Method ms[] = c.getDeclaredMethods();
for(Method m: ms){
if(m.isAnnotationPresent(MyTest.class)){
System.out.println("执行:"+m.getName());
m.invoke(obj, null);
}
}

}

}



/////////////////////////////////////////////////////////////////////////////////////////////////////////////

测试:

import org.junit.Test;

public class Demo {

@MyTest
public void t1(){
System.out.println("111aaaa1111111");
}

public void aa(){
System.out.println("22222222222222");
}

@MyTest
public void t3(){
System.out.println("33333bbb3333333");
}

}

//////////////////////////////////////////////////////////////////////////////////

自己写的一个MyTest的注解

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


@Retention(RetentionPolicy.RUNTIME)// 必须声明成RUNTIME,我们的程序才能识别
@Target({ElementType.METHOD})//定义在方法上的注解
public @interface MyTest {
}

猜你喜欢

转载自blog.csdn.net/qq_35307947/article/details/80429725