TestNG で「無効化」テストを制御できるようにする方法が 2 つあります。
注意すべき非常に重要な違いは、指定した条件に基づいて 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からの1行です。
<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>