import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestCase
{
String value();
}
注解本身,不多说。
public class MyClass
{
@TestCase(value = "method1")
public String method1(String s)
{
return s;
}
public String method2(String s)
{
return s;
}
@TestCase(value = "method3")
public String method3(String s)
{
return s;
}
}
这个是我们的被测试类,给需要被测试的方法加上注解,并提供对应的value
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestMyClass
{
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException
{
Class clazz = Class.forName("MyClass");
Method[] methods = clazz.getDeclaredMethods();
for(Method method : methods)
{
if(method.isAnnotationPresent(TestCase.class))
{
TestCase tc = method.getAnnotation(TestCase.class);
String s = (String) method.invoke(clazz.newInstance(), tc.value());
System.out.println(s);
}
}
}
}
自动测试类,完全不知道被测试的方法是什么,只关注返回的s是否正确就OK。
以上。