一种解决方案可能是在测试类中声明一个String 名称数组,然后按顺序执行。如果您没有并行运行测试,这将起作用。
否则,您可以使用@Factory 注解,它可以从数据提供者那里获取输入,然后创建测试对象。
@Factory(dataProvider = "data")
public Object[] createInstances(String val, String name) {
return new Object[] { new MyTest(name) };
}
@DataProvider
public Object[][] data() {
return new Object[][] { { "a", "one" }, { "b", "two" } };
}
因此,您需要在测试类中使用 name 字段,该字段将使用构造函数进行设置。结合link 中建议的代码来设置测试名称,您可以这样做:
public class MyTest implements ITest {
private String name;
private ThreadLocal<String> testName = new ThreadLocal<>();
public MyTest() {
}
public MyTest(String name) {
this.name = name;
}
@Factory(dataProvider = "data")
public Object[] createInstances(String name) {
return new Object[] { new MyTest(name) };
}
@DataProvider
public Object[][] data() {
return new Object[][] { { "one" }, { "two" } };
}
@BeforeMethod
public void beforeMethod(Method method) {
testName.set(method.getName() + "_" + name);
}
@Test
public void test() {
System.out.println(name);
}
@Override
public String getTestName() {
return testName.get();
}
}
编辑:不使用Factory,可以如下实现。这就需要在ITestContext中设置相关细节:
@DataProvider
public Object[][] data(ITestContext ctx) {
ctx.setAttribute("names", new String[]{"one", "two"});
ctx.setAttribute("index", 0);
return new Object[][] { {"val1", "data1"}, {"val2", "data2"} };
}
现在在beforeMethod 中也注入ITestContext:
@BeforeMethod
public void beforeMethod(ITestContext ctx, Method method) {
testName.set(method.getName() + "_" + getName(ctx));
}
// Create a helper method getName.
private static String getName(ITestContext ctx) {
int index = (int) ctx.getAttribute("index");
// get the name based on the current index.
String name = ((String[]) ctx.getAttribute("names"))[index++];
// update the attribute with the incremented index.
ctx.setAttribute("index", index);
return name;
}
@Test(dataProvider = "data")
public void yourTest(String val, String data) {
// .............
}
注意:当测试并行运行时,这将无法正常工作。