<test name="abc">
<classes>
<class name="myClass">
**<exclude name="testMethod" invocation-numbers="4"/>**
</class>
</classes>
</test>
上面的testng XML简单地排除了&#34; testMethod&#34;作为一个整体。但是,如果我更换&#34;排除&#34;使用&#34; include&#34;,它只能正确运行数据提供程序的第5次迭代作为测试数据。当这是include的情况时,当我把exclude放在一起时,testng应该运行&#34; testMethod&#34;的所有迭代。排除数据提供者的第5次迭代。但它只是将这种方法排除在外。为什么会这样?应该达到我期望的解决方法是什么?
答案 0 :(得分:1)
AFAIK,您无法通过testng.xml文件执行此操作。
很容易指定要执行的迭代而不必知道数据集大小,但是在排除特定迭代时不可能这样做。
我能想到的最简单方法是在数据提供程序中插入此过滤逻辑。这是一个示例,向您展示如何执行此操作:
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class SampleTestClass {
@Test(dataProvider = "dp")
public void testMethod(int value) {
System.out.println("Value is " + value);
}
@DataProvider(name = "dp")
public Object[][] getData() {
Object[][] data = new Object[][]{
{1},
{2},
{3},
{4},
{5}
};
//Calculate how many parameters we will be providing the @Test method for every iteration.
int numberOfParameters = data[0].length;
//Get the list of iterations to exclude from the user as comma separated values
//Here for the sake of example we are simulating that only the 3rd iteration needs to be excluded.
String exclude = System.getProperty("exclude", "3");
if (exclude == null || exclude.trim().isEmpty()) {
return data;
}
//Translate that comma separated values into a list of integers
List<Integer> excludeValues = Arrays.stream(exclude.split(","))
.map(Integer::parseInt).collect(Collectors.toList());
Object[][] finalData = data;
//Now nullify all the rows which we were asked to exclude so that its easy for us to filter out all the non
//null values.
excludeValues.forEach(value -> finalData[value] = null);
Object[] newData = Arrays.stream(data).filter(Objects::nonNull).collect(Collectors.toList()).toArray();
//Lets copy the contents back to the original array
data = new Object[newData.length][numberOfParameters];
for (int i=0;i<newData.length;i++) {
data[i] = (Object[]) newData[i];
}
return data;
}
}