反射加注解案例之测试框架的搭建

发布时间:2022-08-19 14:20

1.自定义测试注解

import java.lang.annotation.*;

@Target({ElementType.METHOD,ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface check {

}

2.定义待测试类(这里就简单的为计算器的加减乘除)

import annotation.check;
public class Calculator {
    private int a, b;
    public Calculator(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public Calculator() {


    }
    @check
    public int add() {
        return a + b;
    }

    @check
    public int jianfa() {
        return a - b;
    }

    @check
    public int chengfa() {
        return a * b;
    }

    @check
    public int chufa() {
        return a / b;
    }

    @check
    public String zifuchuan() {
        String temp;
        temp = "+++";
        return temp;
    }
}

3.测试框架核心代码

import Entity.Calculator;
import annotation.check;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 1. TODO
 2.  1.使用注解框架对软件进行测试
 3.  2.知识点:反射,注解
 */
public class TestAnnotation {
    public static void main(String[] args)throws Exception{
        int number=0;
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("bug.txt"));
        Class<Calculator> calculatorClass = Calculator.class;
        // 1.反射创建calculator
        Constructor<Calculator> constructor = calculatorClass.getConstructor(int.class,int.class);
        Calculator calculator = constructor.newInstance(1,0);
        //2.反射获取method方法
        Method[] methods = calculatorClass.getMethods();
        for (Method method : methods) {
            if(method.isAnnotationPresent(check.class)){
                try {
                    method.invoke(calculator);
                } catch (Exception e) {
                    number++;
                    bufferedWriter.write(method.getName()+"出现了异常!");
                    bufferedWriter.newLine();
                    bufferedWriter.write("异常名称:"+e.getCause().getClass().getSimpleName());
                    bufferedWriter.newLine();
                    bufferedWriter.write("报错原因:"+e.getCause().getMessage());
                    bufferedWriter.newLine();
                    bufferedWriter.write("---------------------------------");
                    bufferedWriter.newLine();
                }finally {
                    bufferedWriter.flush();
                }
            }
        }
        bufferedWriter.write("总共检测到:"+number+"个异常!");
        bufferedWriter.close();

    }
}
  1. 实验结果展示:
    反射加注解案例之测试框架的搭建_第1张图片

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号