测试分组

问题描述

我们使用 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;
    }
}    

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

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