测试框架
package cn.itcast.Junit;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
public class add5 {
public static void main(String[] args) throws IOException {
add s = new add();//创建要测试的类对象
Class<? extends add> aClass = s.getClass();//获取测试类的字节码对象
Method[] methods = aClass.getMethods();//获取字节码对象里面所有的方法存到数组当中
BufferedWriter a = new BufferedWriter(new FileWriter("bug.txt"));//创建字符输出流
int o = 0;//定义计数器
for (Method method : methods) {//遍历方法
if (method.isAnnotationPresent(Myanno.class)) {//判断方法是否被Myanno注解
try {//放入可能会引发异常的代码
method.invoke(s);
} catch (Exception e) {//自定义抛出异常所执行的内容
a.write(method.getName() + "方法抛出异常了");//往文件中写入方法名称
a.newLine();//换行的方法 //e.getCause()获取到异常的原因返回throwable getSimpleName()返回源代码中给出的底层类的简称。如果底层类是匿名的则返回一个空字符串。
a.write("抛出的异常名叫" + e.getClass().getName()+" "+e.getCause().getClass().getSimpleName());//获取异常的名称
a.newLine();//换行
a.write("异常的原因时" + e.getCause().getMessage());//getMessage()返回此 throwable 的详细消息字符串。
a.newLine();
o++;
}
}
}
a.write("一共抛出了" + o + "次异常");
a.flush();
a.close();
}
/*写入的文件内容为
method3方法抛出异常了
抛出的异常名叫ArithmeticException
异常的原因时/ by zero
一共抛出了1次异常*/
}
被测试的类
package cn.itcast.Junit;
public class add {
@Myanno
public void method() {
System.out.println(1 *0);
}
@Myanno
public void method1() {
System.out.println(2 * 0);
}
@Myanno
public void method2() {
System.out.println(3 * 1);
}
@Myanno
public void method3() {
System.out.println(4 / 0);
}
}
自定义的注解内容
package cn.itcast.Junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Myanno1 {
String Method();
String name();
}