发布时间: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();
}
}