一种更通用的方法是使用groups
注释来构建自定义值列表:
@DataProvider(name = "excelLoader")
public Object[][] createData(Method m) {
ArrayList<Object[]> excelFiles = new ArrayList<Object[]>;
// iterate over all the groups listed in the annotation
for (String excelFile : ((Test) m.getAnnotation(Test.class)).groups()) {
// add each to the list
excelFiles.add(new Object[] { excelFile });
}
// convert the list to an array
return excelFiles.toArray(new Object[excelFiles.size()]);
}
@Test(dataProvider = "excelLoader", groups = { "data1", "data2" })
public void test1(String excelFile) {
// we will test "data1.xls" and "data2.xls" in this test
String testExcelFile = excelFile + ".xls";
}
@Test(dataProvider = "excelLoader", groups = { "data2", "data3" })
public void test2(String excelFile) {
// we will test "data2.xls" and "data3.xls" in this test
String testExcelFile = excelFile + ".xls";
}
或者,您也可以创建自己的注释类,该类接受自定义元素,以便您可以做更多类似的事情:
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD, TYPE, CONSTRUCTOR})
public @interface FilesToTest {
public String[] value() default {};
}
@DataProvider(name = "excelLoader")
public Object[][] createData(Method m) {
ArrayList<Object[]> excelFiles = new ArrayList<Object[]>;
// iterate over all the groups listed in the annotation
for (String excelFile : ((FilesToTest) m.getAnnotation(FilesToTest.class)).value()) {
// add each to the list
excelFiles.add(new Object[] { excelFile });
}
// convert the list to an array
return excelFiles.toArray(new Object[excelFiles.size()]);
}
@Test(dataProvider = "excelLoader")
@FilesToTest({ "data1.xls", "data2.xls" })
public void myTest(String excelFile) {
// we will test "data1.xls" and "data2.xls" in this test
}