[英]how to reset value of groups of a Test method in TestNG when running the programme
已经定义了两个组:
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
如果要在运行时修改TestNG批注值,则可以使用AnnotationTransformer 。
public class MyTransformer implements IAnnotationTransformer {
public void transform(ITest annotation, Class<?> testClass,
Constructor testConstructor, Method testMethod) {
annotation.setGroups(new String[]{"groupB"});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.