gpt4 book ai didi

java - TestNG:根据逻辑跳过迭代

转载 作者:行者123 更新时间:2023-12-02 12:04:41 25 4
gpt4 key购买 nike

我已经看到了许多关于如何跳过整个@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 - 已跳过

最佳答案

通过利用 TestNG 提供的 IHookable 接口(interface),您可以非常轻松地完成此操作。现在,在 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
===============================================

关于java - TestNG:根据逻辑跳过迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com