1 对某个类中某些方法的测试
1.1 声明注解
Check.java
Check注解用于标注是否需要测试
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {}
Pro.java
/**
* @author Tang
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Pro {
String className();//需要执行测试的类
String checkMethod() default "com.tang.annotation.demo.Check";//测试标注check
}
1.2 编写测试Service
@Service
public class AnnotationService {
// 将此处的com.tang.annotation.demo.Calculator换成要测试的类
@Pro(className = "com.tang.annotation.demo.Calculator")
public void check() throws Exception {
// 获得字节码
Class<AnnotationService> cl = AnnotationService.class;
// 获取当前方法
Method methodr = cl.getMethod("check");
// 获取方法上的注解,并得到注解的参数
Pro pro = methodr.getAnnotation(Pro.class);
String className = pro.className();
String checkMethod = pro.checkMethod();
// 获得用于检查的注解标记
@SuppressWarnings("unchecked")
Class<? extends Annotation> checkr = (Class<? extends Annotation>) Class
.forName(checkMethod);
// 根据类名获取字节码
Class<?> clazz = Class.forName(className);
Object obj = clazz.newInstance();
// 获得所有方法
Method[] methods = clazz.getMethods();
BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));
// 判断方法上是否有Check注解
for (Method method : methods) {
System.out.print("name:" + method.getName());
if (method.isAnnotationPresent(checkr)) {
// 有,执行
System.out.println(" Anno test in!");
try {
method.invoke(obj);
} catch (Exception e) {
// 捕获异常
bw.write(method.getName() + "方法");
bw.newLine();
bw.write("异常的原因:" + e.toString());
bw.newLine();
bw.write("---------------------");
bw.newLine();
}
} else {
System.out.println(" Anno test out!");
}
}
bw.flush();
bw.close();
}
}
1.3 需要测试的类
public class Calculator {
@Check
public Integer add(Integer a, Integer b) {
System.out.println(1+0);
return a + b;
}
@Check
public Integer del(Integer a, Integer b) {
System.out.println(1-0);
return a - b;
}
@Check
public Integer mul(Integer a, Integer b) {
System.out.println(1*0);
return a * b;
}
@Check
public Integer dev(Integer a, Integer b) {
System.out.println(1/0);
return a / b;
}
}
1.4 测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnnotationServiceTest {
@Autowired
private AnnotationService service;
// 执行测试
@Test
public void testCheck() throws Exception {
service.check();
}
}
执行结果:
name:add Anno test in!
name:mul Anno test in!
name:del Anno test in!
name:dev Anno test in!