如何在运行程序时重置TestNG中Test方法的组值

时间:2017-03-29 06:17:03

标签: java annotations testng

已经定义了两个组:

public class GroupA {

    @BeforeGroups(groups = "groupA")
    public void beforeGroup1(){
        System.out.println("In before GroupA");
    }
}

public class GroupB {

    @BeforeGroups(groups = "groupB")
    public void beforeGroup1(){
        System.out.println("In beforeGroupB");
    }
}

测试类是:

public class TestCls {

    @Test(groups="groupA")
    public void test(){
        System.out.println("In Test Class");
    }

}

在BeforeSuite的代码中,尝试将组的值重置为" groupB"使用以下代码,它没有按预期工作。

public class Suite {

    @BeforeSuite()
    public void test() throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();      
        CtClass ct = pool.get(TestCls.class.getName());   

        //reset attribute groups from groupA to groupB 
        CtMethod ctMethod = ct.getDeclaredMethod("test");
        MethodInfo ctMethodInfo = ctMethod.getMethodInfo();
        ConstPool cp = ctMethodInfo.getConstPool(); 

        //reset attribute groups from groupA to groupB
        AnnotationsAttribute attribute = (AnnotationsAttribute)ctMethodInfo.getAttribute(AnnotationsAttribute.visibleTag);
        Annotation annotation = attribute.getAnnotation("org.testng.annotations.Test"); 
        ArrayMemberValue arrayMemberValue = new ArrayMemberValue(cp);
        StringMemberValue[] memberValues = new StringMemberValue[]{new StringMemberValue("groupB", cp)};
        arrayMemberValue.setValue(memberValues);
        annotation.addMemberValue("groups", arrayMemberValue);  
        attribute.setAnnotation(annotation);  
        ctMethodInfo.addAttribute(attribute);

        //check if groups changed successfully
        Annotation annotation2 = attribute.getAnnotation("org.testng.annotations.Test"); 
        MemberValue[] text = ((ArrayMemberValue)annotation2.getMemberValue("groups")).getValue();  
        System.out.println("the groups after modified is " + text[0]); 
    }
}

输出

the groups after modified is groupB
In beforeGroup1
In Test Class

1 个答案:

答案 0 :(得分:1)

如果要在运行时修改TestNG注释值,可以使用AnnotationTransformer

(public_path())