TestNG 允许您在运行时修改所有注解的内容。如果源代码中的注解大部分时间都是正确的,这将特别有用,但在少数情况下您希望覆盖它们的值。
为了实现这一点,您需要使用 Annotation Transformer。
Annotation Transformer 是一个实现以下接口的类:
public interface IAnnotationTransformer {/*** This method will be invoked by TestNG to give you a chance* to modify a TestNG annotation read from your test classes.* You can change the values you need by calling any of the* setters on the ITest interface.** Note that only one of the three parameters testClass,* testConstructor and testMethod will be non-null.** @param annotation The annotation that was read from your* test class.* @param testClass If the annotation was found on a class, this* parameter represents this class (null otherwise).* @param testConstructor If the annotation was found on a constructor,* this parameter represents this constructor (null otherwise).* @param testMethod If the annotation was found on a method,* this parameter represents this method (null otherwise).*/public void transform(ITest annotation, Class testClass,Constructor testConstructor, Method testMethod);}
与所有其他 TestNG 侦听器一样,您可以在命令行或使用 ant 指定此类:
java org.testng.TestNG -listener MyTransformer testng.xml
或以编程方式:
TestNG tng = new TestNG();tng.setAnnotationTransformer(new MyTransformer());// ...
当调用方法transform() 时,您可以调用ITest 测试参数上的任何设置器以在 TestNG 进一步进行之前更改其值。
例如,以下是您将如何覆盖属性invocationCount但仅在您的一个测试类的测试方法invoke()上:
public class MyTransformer implements IAnnotationTransformer {public void transform(ITest annotation, Class testClass,Constructor testConstructor, Method testMethod){if ("invoke".equals(testMethod.getName())) {annotation.setInvocationCount(5);}}}
IAnnotationTransformer只允许您修改@Test注释。如果您需要修改另一个TestNG的注释(配置注释,@Factory或@dataProvider),使用IAnnotationTransformer2。
