04.模拟Junit中的@Test

 

TestRunner.java
package com.exp.annotation;

import sun.security.jca.GetInstance;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class TestRunner {

    public static void main(String[] args) throws Exception{
        //执行Demo里的两个单元测试的方法

        //1.通过反射来获取方法
        Method[]  methods = Demo.class.getMethods();
        for(Method m : methods ){
            if(m.getName().startsWith("test")){
                //2.通过反射来获取方法上面的注解
                MyTest MyTest = m.getAnnotation(MyTest.class);
                if(MyTest != null){
                    //3.执行注解下面的方法
                    System.out.println(MyTest.name());
                    m.invoke(Demo.class.newInstance());
                }
            }
        }
        // 2.通过反射来获取方法
}
}

 

Demo.java

package com.exp.annotation;

public class Demo {

    @MyTest(name="zhangsan")
    public void test1(){
        System.out.println("此处运行test1方法..");
}
    @MyTest()
    public void test2(){
        System.out.println("此处运行test2方法..");
    }

    public void test3(){
        System.out.println("此处运行test3方法..");
    }
}

 

MyTest.java
package com.exp.annotation;

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

//注解的策略,让它保留在运行的时候   -> 注解生存周期  -> 注解还在字节码上面
@Retention(RetentionPolicy.RUNTIME) 
public @interface MyTest {
    String name() default "exp";
}

 

gyf

package com.gyf.annotation;

import java.lang.reflect.Method;

/**
 * 注解的工作原理
 * 1.通过反射获取方法
 * 2.通过方法获取方法上面声明的注解对象
 * 3.通过注解对象可以获取注解声明一些参数
 * 4.通过反射来调用方法
 */
public class TestRunner {

    public static void main(String[] args)throws Exception {
        //执行Demo里单元测试两个方法
        //1.通过反射来获取方法
        Method[] methods = Demo.class.getMethods();
        for(Method m : methods){
            if(m.getName().startsWith("test")){//只有以test开头的方法才是单元测试方法
                //2.通过反射来获取方法上面注解
                MyTest myTest = m.getAnnotation(MyTest.class);
                System.out.println(m.getName() + " 是否有MyTest注解:" + myTest);
                if(myTest != null){
                    System.out.println("name=" + myTest.name());
                    //执行注解下面的方法
                    m.invoke(Demo.class.newInstance());
                }
            }
        }


    }
}

 

posted @ 2019-03-17 01:21  expworld  阅读(399)  评论(0)    收藏  举报