天天看點

寫一個自己的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 {

}