我知道两种方法可以让你控制在TestNG中“禁用”测试。
需要注意的区别是:SkipException会退出所有后续测试,而实现IAnnotationTransformer使用反射来禁用个别测试,根据您指定的条件。我将解释SkipException和IAnnotationTransfomer的用法。
SKIP Exception示例
import org.testng.*;
import org.testng.annotations.*;
public class TestSuite
{
boolean myCondition;
@BeforeMethod
public void before(Method methodName){
if(myCondition)
throw new SkipException();
}
@Test(priority = 1)
public void test1(){}
@Test(priority = 2)
public void test2(){}
@Test(priority = 3)
public void test3(){}
}
IAnnotationTransformer 示例
这个示例有点复杂,但其背后的思想是一个被称为反射的概念。
维基 - http://en.wikipedia.org/wiki/Reflection_(computer_programming)
首先实现IAnnotation接口,将其保存在*.java文件中。
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
public class Transformer implements IAnnotationTransformer {
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod){
if (disableMe()){
annotation.setEnabled(false);
}
}
private boolean disableMe() {
}
}
然后在你的测试套件 Java 文件中,在 @BeforeClass 函数中执行以下操作:
import org.testng.*;
import org.testng.annotations.*;
@BeforeClass
public void before(){
TestNG testNG = new TestNG();
testNG.setAnnotationTransformer(new Transformer());
}
@Test(priority = 1)
public void test1(){}
@Test(priority = 2)
public void test2(){}
@Test(priority = 3)
public void test3(){}
最后一步是确保您在build.xml文件中添加一个监听器。
我的最终结果看起来像这样,这只是build.xml中的一行:
One last step is to ensure that you add a listener in your build.xml file.
Mine ended up looking like this, this is just a single line from the build.xml:
<testng classpath="${test.classpath}:${build.dir}" outputdir="${report.dir}"
haltonfailure="false" useDefaultListeners="true"
listeners="org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter,Transformer"
classpathref="reportnglibs"></testng>