ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-05-04 18:02:39  阅读:17  来源: 互联网

标签:lang 写个 java writer Check import 注解 public


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

计算器类

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();
    }
}

标签:lang,写个,java,writer,Check,import,注解,public
来源: https://www.cnblogs.com/codegzy/p/14729923.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有