2017-03-29 64 views
0

兩組已經定義當復位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 
+0

輸出爲「修改後的組是B組,A組中之前,在測試類」,不運行B組 – zhuxy

回答

1

如果你想在運行時修改TestNG的標註值,你可以使用一個AnnotationTransformer

public class MyTransformer implements IAnnotationTransformer { 
    public void transform(ITest annotation, Class<?> testClass, 
     Constructor testConstructor, Method testMethod) { 
    annotation.setGroups(new String[]{"groupB"}); 
    } 
} 
+0

如何「BeforeSuite」後涉及該方法,尤其是如何獲得註釋 – zhuxy

+0

爲什麼BeforeSuite之後你想要它嗎? 「ITest」是Test註釋的內部表示。 – juherr