使用类反射写一个自己的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 MyJUnit {
	
}

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

public class RunJUnit {
	public static void main(String[] args) {
		System.out.println("请输出你需要测试的类: ");
		Scanner scanner = new Scanner(System.in);
		String path = scanner.nextLine();
		try {
			Class<?>clazz = Class.forName(path);
			Object obj = clazz.newInstance();
			Method[]methods = clazz.getDeclaredMethods();
			for (Method method : methods) {
				if(null != method.getAnnotation(MyJUnit.class)) {
					method.invoke(obj);
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		scanner.close();
	}
}

public class TestMyJUnit {
	@MyJUnit
	public void test1() {
		System.out.println("111111111111");
	}
	
	public void test2() {
		System.out.println("22222222222222");
	}
	
	@MyJUnit
	public void test3() {
		System.out.println("3333333333333");
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38238041/article/details/80624597