待测方法
待测的方法是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中