我已经看到很多关于如何跳过整个@Test 的答案,但我试图跳过特定的迭代,而不必向现有的几十个添加额外的元数据测试:
public class TestNgPlayground {
public static final DayOfWeek SOME_CONST = DayOfWeek.TUESDAY;
@DataProvider
public Object[][] getStuff(){
return new Object[][] {
{ "param1", DayOfWeek.MONDAY}, // Skip this
{ "param2", DayOfWeek.TUESDAY }, // Run this
{ "param3", DayOfWeek.WEDNESDAY } // Skip this
};
}
// Ideally I want to detect and Skip in @BeforeMethod / @BeforeClass
@BeforeMethod // testArgs fetches the DataProvider values
public void setUp(Object[] testArgs,ITestResult result ){
DayOfWeek dataProviderValue = (DayOfWeek) testArgs[1];
if(dataProviderValue!= SOME_CONST ) {
// throw new SkipException("skip test"); // No good - skips the entire Test
// result.setStatus(ITestResult.SKIP); // Doesn't do anything
}
}
@Test(dataProvider = "getStuff")
public void testt(String param1, DayOfWeek param2){
// some testing
}
// 2nd best option - overwrite to Skip after test has run,
// though time has been wasted
@AfterMethod
public void tearDown(ITestResult result){
DayOfWeek dow = (DayOfWeek) result.getParameters()[1];
if(dow != SOME_CONST){
result.setStatus(ITestResult.SKIP); // Doesn't do anything either... ?
}
}
}
对于上面的例子,我想要显示最终报告:
迭代1 - 跳过
迭代2 - 通过
迭代3 - 跳过
答案 0 :(得分:1)
通过利用TestNG提供的IHookable接口,您可以非常轻松地完成此操作。现在,在run()
方法中,您将能够决定要对特定迭代执行的操作,甚至相应地更改状态。
以下是展示如何执行此操作的示例。
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.time.DayOfWeek;
public class TestNgPlayground implements IHookable {
private static final DayOfWeek SOME_CONST = DayOfWeek.TUESDAY;
@DataProvider
public Object[][] getStuff() {
return new Object[][]{
{"param1", DayOfWeek.MONDAY}, // Skip this
{"param2", DayOfWeek.TUESDAY}, // Run this
{"param3", DayOfWeek.WEDNESDAY} // Skip this
};
}
@Test(dataProvider = "getStuff")
public void testt(String param1, DayOfWeek param2) {
System.err.println("[" + param1 + ", " + param2 + "]");
}
@Override
public void run(IHookCallBack callBack, ITestResult testResult) {
Object[] parameters = callBack.getParameters();
DayOfWeek dataProviderValue = (DayOfWeek) parameters[1];
if (dataProviderValue != SOME_CONST) {
callBack.runTestMethod(testResult);
} else {
testResult.setStatus(ITestResult.SKIP);
}
}
}
这是输出:
[param1, MONDAY]
[param3, WEDNESDAY]
Test ignored.
===============================================
Default Suite
Total tests run: 3, Failures: 0, Skips: 1
===============================================