java基础:利用注解编写简单的方法测试

待测方法

待测的方法是CheckMethod类中的加减乘除
不想一个一个去测试里面是否有错误
所有编写一个类来统一进行测试
首先给需要测试的方法加上@Check(自己写的注解)注解

/**
 * date:2020-04-18
 * author:zhangxs
 */
public class CheckMethod {
//    加法

    @Check
    public void add(){
        System.out.println(1+1);
    }

//    减法

    @Check
    public void sub(){
        System.out.println(1-1);
    }

//    乘

    @Check
    public void mul(){
        System.out.println(1*2);
    }

//    除法

    @Check
    public void div(){
        System.out.println(1/0);
    }

    public void show(){
        System.out.println("这是其他方法!!!");
    }


}

@Check注解
这个注解主要的作用就是来区分哪些方法需要被测试
如果有这个方法就进行测试

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

/**
 * date:2020-04-18
 * author:zhangxs
 */

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

测试类
测试有Check注解的方法
方法如果有错误就打印错误到bug.txt

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

/**
 * date:2020-04-18
 * author:zhang
 */
public class Test {
    public static void main(String[] args) throws IOException {

//        创建对象
        CheckMethod checkMethod = new CheckMethod();

//        获取字节码对象
        Class m = checkMethod.getClass();

//        获取所有方法
        Method[] methods = m.getMethods();
        
//        检验方法是否有错误
//        有错误就生成bug.txt
        int errorNum = 0;
        BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
        for (Method method :
                methods) {
//      判断是否有Check注解
            if (method.isAnnotationPresent(Check.class)) {
//             执行方法
                try {
                    method.invoke(checkMethod);
                } catch (Exception e) {
//                    记录错误
                    errorNum++;
                    bw.write(method.getName() + "方法出现异常了");
                    bw.newLine();
                    bw.write("异常名称:" + e.getCause().getClass().getSimpleName());
                    bw.newLine();
                    bw.write("异常原因:" + e.getCause().getMessage());
                    bw.newLine();
                    bw.write("本次测验结束一共有" + errorNum + "个错误");
                    bw.flush();
                    bw.close();
                }
            }
        }
    }
}

结果就会写在bug.txt中
错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值