发布时间: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();
}
}
企鹅够牛,大事不断:腾讯音乐遭“投资者律师代表团”调查、大数据组件TubeMQ宣布开源、1千万美元领投英国AI企业SenSat...
python 通过dict(zip)和{}的方式构造字典的方法
Java项目:校园宿舍管理系统(java+Springboot+Vue+maven+redis+Mysql)
ebook下载 | 灵雀云发布《 企业高管IT战略指南——为何选择容器与Kubernetes》
React + Node.js 全栈实战教程 - 手把手教你搭建「文件上传」管理后台
权限系统控制到按钮级别开源推荐 Spring Boot-Shiro-Vue