相信用过 Junit 的朋友都知道 JUnit是Java的一个单元测试框架,在实现自动单元测试的情况下可以大大的提高开发的效率,那么我们如何自定义一个@Test注解呢?
首先,我们先写一个@Test注解,如下:
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Woo_home
* @create by 2019/9/18
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}
@Test注解类型的声明就是它自身通过Retention和Target注解进行了注解。注解类型声明中的这种注解被称为元注解(meta-annotation)。@Retention(RetentionPolicy.RUNTIME)元注解表明,@Test注解应该在运行时保留。如果没有保留,测试工具就无法知道@Test注解。@Target(ElementType.METHOD)元注解表明,@Test注解只在方法声明中才是合法的:它不能运用到类声明。域声明或者其他程序元素上
在应用中使用@Test注解
package demo;
import annotation.Test;
/**
* @author Woo_home
* @create by 2019/9/18
*/
public class TestDemo {
@Test
public void hello(){
System.out.println("Hello World");
}
}
编写测试运行类
package utils;
import annotation.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Woo_home
* @create by 2019/9/18
*/
public class RunTests {
public static void main(String[] args) throws Exception{
int tests = 0; //记录成功
int passed = 0;//记录失败
Class testClass = Class.forName("demo.TestDemo"); //反射带有@Test注解的类
for (Method m : testClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(Test.class)){ //Test是定义的注解类,isAnnotationPresent方法告知该工具运行哪些方法
tests++;
try {
m.invoke(testClass.newInstance()); //通过调用invoke反射式地运行类中所有标注了@Test的方法
passed++;
}catch (InvocationTargetException wrappedExc){
Throwable exc = wrappedExc.getCause();
System.out.println(m + " failed: " + exc);
}catch (Exception exc){
System.out.println("INVALID @Test: " + m);
}
}
}
System.out.printf("Passed: %d, Failed: %d%n",tests,tests-passed);
}
}
我们运行这个类就会打印出标注有@Test注解的方法
但是标注有@Test的类只能用于没有返回值的方法,如果用了有返回值的方法就会报错
,比如:
package demo;
import annotation.Test;
/**
* @author Woo_home
* @create by 2019/9/18
*/
public class TestDemo {
@Test
public int test1(int i){
i = 0;
return i;
}
@Test
public void hello(){
System.out.println("Hello World");
}
}
运行测试运行类后会有一个失败