实例需求需求:模拟junit4中的用例结构,自定义一个标签作为测试用例的标识。
在junit4中注解@test表示测试用例,每一个测试用例的本质就是测试类中的一个方法,即:
@test public void test() { fail(not yet implemented); }
具体要求:
测试类是默认构造方法
通过标签mytag作为方法是否为用例的标识
作为用例的方法必须是无参的
写一个方法runcase(string pkgname),使其能够完成对指定类中测试用例的调用工作
注解设计首先需要定义一个注解mytag,代码如下:
import java.lang.annotation.retention; import java.lang.annotation.target; import java.lang.annotation.elementtype; import java.lang.annotation.retentionpolicy; @retention(retentionpolicy.runtime) @target(elementtype.method) public @interface mytag{ string name(); }
测试用例设计模拟junit4框架,写一个测试类,其中login、info、logout是无参方法,而test是有参方法
public class testtag{ @mytag(name=case1) public void login(){ system.out.println(login); } @mytag(name=case2) public void info(){ system.out.println(info); } @mytag(name=case3) public void logout(){ system.out.println(logout); } @mytag(name=case4) public void test(string p){ system.out.println(logout); } }
运行类的设计思路因为测试类是默认构造方法,所以使用如下api,完成类实例化
class<?> clazz = class.forname(pkgname) object obj = clazz.newinstance();
因为测试类中有很多方法,我们需要获取所有的方法并按照规则进行过滤,代码如下:
method[] methods = clazz.getmethods(); for (method method : methods) { //过滤规则 }
判断方法的标签是否为mytag,代码如下:
if(method.getannotation(mytag.class) != null)
判断方法是否没有参数,代码如下:
if(method.getparametercount()==0)
运行方法,代码如下:
method.invoke(obj)
完整代码public static void runcase(string pkgname) throws illegalaccessexception,illegalargumentexception, invocationtargetexception, instantiationexception,classnotfoundexception { class<?> clazz = class.forname(pkgname); object obj = clazz.newinstance(); method[] methods = clazz.getmethods(); for (method method : methods) { if(method.getannotation(mytag.class) != null&& method.getparametercount()==0) { method.invoke(obj); //调用方法 system.out.println(测试用例名称是:+method.getname()); } } }
运行代码,输出如下:
logout
测试用例名称是:logout
login
测试用例名称是:login
info
测试用例名称是:info
以上就是怎么使用java注解和反射实现junit4调用的详细内容。
