gpt4 book ai didi

java - 运行程序时如何重置 TestNG 中测试方法组的值

转载 作者:行者123 更新时间:2023-12-02 13:34:23 24 4
gpt4 key购买 nike

已经定义了两个组:

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"});
}
}

关于java - 运行程序时如何重置 TestNG 中测试方法组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43085739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com