我知道有两种方法可以让您控制 TestNG 中的“禁用”测试。
需要注意的非常重要的区别是,在实现 IAnnotationTransformer 时,SkipException 将中断所有后续测试,并根据您指定的条件使用反射来禁用单个测试。我将解释 SkipException 和 IAnnotationTransfomer。
跳过异常示例
import org.testng.*;
import org.testng.annotations.*;
public class TestSuite
{
// You set this however you like.
boolean myCondition;
// Execute before each test is run
@BeforeMethod
public void before(Method methodName){
// check condition, note once you condition is met the rest of the tests will be skipped as well
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 {
// Do not worry about calling this method as testNG calls it behind the scenes before EVERY method (or test).
// It will disable single tests, not the entire suite like SkipException
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod){
// If we have chose not to run this test then disable it.
if (disableMe()){
annotation.setEnabled(false);
}
}
// logic YOU control
private boolean disableMe() {
}
}
然后在您的测试套件 java 文件中,在 @BeforeClass 函数中执行以下操作
import org.testng.*;
import org.testng.annotations.*;
/* Execute before the tests run. */
@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 中的一行:
<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>