TestNG参数化之@DataProvider传参

时间:2023-01-31 18:15:15

@parameters适合传递简单少量参数,复杂参数一般使用@DataProvider传递

@DataProvider语法:

@DataProvider(name = "dataproviderName") public Object[][] createData([Method m]) { return Array; }

@Test(dataprovider="dataproviderName"[, dataProviderClass = dataProviderClassName.class]) 
public void test(parameters...){ }

 

1.简单返回Array

test.java

    //This method will provide data to any test method that declares that its Data Provider
    //is named "test1"
    @DataProvider(name = "test1") public Object[][] createData1() { return new Object[][] { { "Cedric", new Integer(36) }, { "Anne", new Integer(37)}, };
    }
     
    //This test method declares that its data should be supplied by the Data Provider
    //named "test1"
    @Test(dataProvider = "test1") public void verifyData1(String n1, Integer n2) {
     System.out.println(n1 + ": " + n2);
    }

2.独立DataProvider类

StaticProvider.java——提供数据的类
public class StaticProvider {
  @DataProvider(name = "create")
  public static Object[][] createData() {
    return new Object[][] {
   { "Cedric", new Integer(36) },
   { "Anne", new Integer(37)},
 };
}

test.java

//This test method declares that its data should be supplied by the Data Provider
//named "test1"
@Test(dataProvider = "create", dataProviderClass = StaticProvider.class) public void verifyData1(String n1, Integer n2) {
 System.out.println(n1 + " " + n2);
}

 

3.含参数的DataProvider类_参数为调用dataprovider的方法名

StaticProvider.java 
public class StaticProvider {
 @DataProvider(name = "create") public static Object[][] createData(Method m) {         return getData(m.getName()); } public static Object[][] getData(String methodName){
            .........
            ...........
            return Object[][];
      }      
}    

test.java

        //This test method declares that its data should be supplied by the Data Provider
        //named "test1"
        @Test(dataProvider = "create", dataProviderClass = StaticProvider.class)
        public void test1(String n1, Integer n2) {
         System.out.println(n1 + " " + n2);
        }

注意:dataProvider只能对使用@Test的方法使用