java利用注解写个简单的测试框架

要求:利用注解测试某个类中的方法,并且将异常信息写入文件中

计算器类

public class Caculator {
    @Check
    public int add() {
        return 1 + 3;
    }

    @Check
    public int sub() {
        return 3 - 1;
    }

    @Check
    public int mul() {
        return 3 * 3;
    }

    @Check
    public int div() {
        int b = 8 / 0;
        return b;
    }
}


自定义注解

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {

}

测试框架类

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//简单测试框架
public class CheckTest {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, IOException {
        Caculator caculator = new Caculator();
        Class<? extends Caculator> aClass = caculator.getClass();
        //将异常信息写入文件中
        BufferedWriter writer = new BufferedWriter(new FileWriter("bug.txt"));
        //获得其所有方法
        Method[] methods = aClass.getMethods();
        //判断方法是否有check注解
        for (Method method : methods) {
            if (method.isAnnotationPresent(Check.class)){
                try {
                    method.invoke(caculator);
                } catch (Exception e) {
                    writer.write(method.getName()+"出现异常了");
                    writer.newLine();
                    writer.write("异常原因:"+e.getCause().getClass().getSimpleName());
                    writer.newLine();
                    writer.write("异常信息:"+e.getCause().getMessage());
                    writer.newLine();
                    writer.write("---------------------");
                }
            }
        }
        writer.flush();
        writer.close();
    }
}

上一篇:Servlet基础


下一篇:神经网络学习小记录1——Pytorch当中Tensorboard的使用