【发布时间】:2015-01-29 21:37:21
【问题描述】:
当某些环境变量的值不可接受时,我想提供一种优雅的机制来跳过选定的测试。我选择添加自己的注释@RunCondition 来定义特定测试允许的值。然后我为 TestNG 创建了自己的侦听器,当环境变量的值不在注释参数中定义的允许范围内时,它将测试标记为禁用。
我的代码如下:
public class ExampleTest {
private int envVar;
@BeforeClass
public void setUp() {
//set up of some environmental variables which depends on external source
StaticContext.setVar(getValueFromOuterSpace());
}
@RunCondition(envVar=2)
@Test
public void testFoo(){
}
}
public class SkipTestTransformer implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation iTestAnnotation, Class aClass, Constructor constructor, Method method) {
RunCondition annotation = method.getAnnotation(RunCondition.class);
int[] admissibleValues = annotation.envVar();
for (int val : admissibleValues) {
if (StaticContext.getVar() == val) {
return; // if environmental variable matches one of admissible values then do not skip
}
}
iTestAnnotation.setEnabled(false);
}
}
public @interface RunCondition {
int[] envVar();
}
我的代码运行良好,但有一个小问题是 transform 方法在 setUp 之前调用,即 @BeforeClass 函数。在所有测试初始化之后还有其他可能运行 Transformer 吗?我认为这样的解决方案优雅而清晰,我不希望任何丑陋的 if 子句达到我的目标......
我正在使用 Java 7 和 TestNG v5.11。
【问题讨论】: