TestNg分组

TestNg grouping

我们使用 testNg 作为我们的测试框架,其中我们使用 @groups 注释进行 运行 特定测试。我们如何自定义此注释以使构建目标中指定的组在 'AND' 中而不是 'OR' 中被考虑。

@groups({'group1', 'group2'})
public void test1

@groups({'group1', 'group3'})
public void test2

如果我们将组作为 {group1,group2} 传递,那么 test1 应该是唯一被触发的测试用例。目前,使用默认实现 test1test2 都会被触发,因为注释考虑了 'or' 中的两个组而不是 'and'

当前的实现是这样的,如果测试方法中指定的任何一个组与套件文件中指定的任何一个组匹配,那么测试将包含在 运行 .

目前没有规定将“任何匹配”的这种实现方式更改为“所有匹配”。但是您可以使用 IMethodInterceptor.

实现相同的效果

(此外,对于所讨论的具体示例,您可以通过提及 group3 作为排除组来达到预期的结果。但这在许多其他情况下不起作用)。

import java.util.Arrays;

public class MyInterceptor implements IMethodInterceptor {
    
    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        String[] includedGroups = context.getIncludedGroups();
        Arrays.sort(includedGroups);

        List<IMethodInstance> newList = new ArrayList<>();
        for(IMethodInstance m : methods) {
            String[] groups = m.getMethod().getGroups();
            Arrays.sort(groups);

            // logic could be changed here if exact match is not required.
            if(Arrays.equals(includedGroups, groups)) {
                newList.add(m);
            }
        }

        return newList;
    }
}    

然后在您的测试 class 之上,使用 @Listeners 注释。

@Listeners(value = MyInterceptor.class)
public class MyTestClass {
}