TestNG 允许您在运行时修改所有注解的内容。如果源代码中的注解大部分时间都是正确的,这将特别有用,但在少数情况下您希望覆盖它们的值。
    为了实现这一点,您需要使用 Annotation Transformer。
    Annotation Transformer 是一个实现以下接口的类:

    1. public interface IAnnotationTransformer {
    2. /**
    3. * This method will be invoked by TestNG to give you a chance
    4. * to modify a TestNG annotation read from your test classes.
    5. * You can change the values you need by calling any of the
    6. * setters on the ITest interface.
    7. *
    8. * Note that only one of the three parameters testClass,
    9. * testConstructor and testMethod will be non-null.
    10. *
    11. * @param annotation The annotation that was read from your
    12. * test class.
    13. * @param testClass If the annotation was found on a class, this
    14. * parameter represents this class (null otherwise).
    15. * @param testConstructor If the annotation was found on a constructor,
    16. * this parameter represents this constructor (null otherwise).
    17. * @param testMethod If the annotation was found on a method,
    18. * this parameter represents this method (null otherwise).
    19. */
    20. public void transform(ITest annotation, Class testClass,
    21. Constructor testConstructor, Method testMethod);
    22. }

    与所有其他 TestNG 侦听器一样,您可以在命令行或使用 ant 指定此类:

    1. java org.testng.TestNG -listener MyTransformer testng.xml

    或以编程方式:

    1. TestNG tng = new TestNG();
    2. tng.setAnnotationTransformer(new MyTransformer());
    3. // ...

    当调用方法transform() 时,您可以调用ITest 测试参数上的任何设置器以在 TestNG 进一步进行之前更改其值。
    例如,以下是您将如何覆盖属性invocationCount但仅在您的一个测试类的测试方法invoke()上:

    1. public class MyTransformer implements IAnnotationTransformer {
    2. public void transform(ITest annotation, Class testClass,
    3. Constructor testConstructor, Method testMethod)
    4. {
    5. if ("invoke".equals(testMethod.getName())) {
    6. annotation.setInvocationCount(5);
    7. }
    8. }
    9. }

    IAnnotationTransformer只允许您修改@Test注释。如果您需要修改另一个TestNG的注释(配置注释,@Factory或@dataProvider),使用IAnnotationTransformer2。