TestNG的IMethodInterceptor监听器详解

来源:互联网 发布:ssd nvme ubuntu 分区 编辑:程序博客网 时间:2024/04/30 03:06

在TestNG的执行过程中,根据测试方法的执行顺序,可以将测试方法分为如下两类:

  • 顺序执行的方法,即依赖于其他测试方法或者被其他测试方法所依赖
  • 执行无特定顺序的方法,即测试方法的执行没有特定的顺序要求,不同的TestNG执行可能有不同的顺序

对于第一类测试方法,其执行顺序不能随意改变,必须符合依赖关系。但是对于第二类测试方法,TestNG提供了IMethodInterceptor监听器,可以改变这些测试方法的执行顺序。

IMethodInterceptor监听器也是继承自ITestNGListener接口,其中唯一定义如下方法:

java.util.List<IMethodInstance> intercept(java.util.List<IMethodInstance> methods, ITestContext context);
注意:只有第二类测试方法能够作为intercept()方法的第一个参数。

           intercept()方法的返回值是经过排序后的测试方法,TestNG将据此顺序执行测试方法。

           intercept()方法的第二个参数可以设置用户信息,便于后续生成测试报表时进行查看。

事实上,TestNG在调用任何测试方法之前,都会调用IMethodInterceptor监听器实例的intercept()方法。

1. IMethodInterceptor监听器的实现示例如下:

public class FastMethodInterceptor implements IMethodInterceptor {public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {  List<IMethodInstance> result = new ArrayList<IMethodInstance>();  for (IMethodInstance m : methods) {    Test test = m.getMethod().getConstructorOrMethod().getAnnotation(Test.class);    Set<String> groups = new HashSet<String>();    for (String group : test.groups()) {      groups.add(group);    }    if (groups.contains("fast")) {      result.add(0, m);    }    else {      result.add(m);    }  }  return result;}}
注意:重写的方法中,属于“fast"组的测试方法被加入到链表的头部,优先执行。

2. 启动TestNG时指定IMethodInterceptor监听器

java org.testng.TestNG -listener test.methodinterceptors.FastMethodInterceptor testng.xml


1 0
原创粉丝点击