一旦 TestNG 计算出调用测试方法的顺序,这些方法将分为两组:
- 方法按顺序运行。这些都是具有依赖关系或依赖关系的测试方法。这些方法将按特定顺序运行。
- 方法没有特定的顺序运行。这些都是不属于第一类的方法。这些测试方法的运行顺序是随机的,并且可以从一次运行到下一次不同(尽管默认情况下,TestNG 将尝试按类对测试方法进行分组)。
为了让你更好地控制属于第二类的方法,TestNG 定义了以下接口:
public interface IMethodInterceptor {
List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context);
}
传入参数的方法列表是所有可以按任意顺序运行的方法。您的拦截方法预计会返回一个类似的IMethodInstance列表,可以是以下任一列表:
- 您在参数中收到的相同列表,但顺序不同。
- 一个较小的IMethodInstance对象列表。
- 更大的IMethodInstance对象列表。
一旦你定义了你的拦截器,你将它作为一个监听器传递给 TestNG。例如:
java -classpath "testng-jdk15.jar:test/build" org.testng.TestNG -listener test.methodinterceptors.NullMethodInterceptor
-testclass test.methodinterceptors.FooTest
例如,这是一个方法拦截器,它将重新排序方法,以便始终首先运行属于“快速”组的测试方法:
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;