我试图使用@DataProvider来运行带有不同参数的@test,但是获得异常

时间:2015-10-18 19:43:28

标签: java testng testng-dataprovider

我想将参数传递给@test以使用不同的数据多次运行。所以我使用@DataProvider重新调整二维Object数组。我有一维字符串,所以首先我将它转换为二维数组,然后为对象赋值。 。但得到以下例外。

public class DtaProvider {

    public static String patchfileName = null;
    public static String[] patchsplit = null;
    public static String temp= null;
    public int number   = 0;

      @DataProvider(name = "getData")
      public Object[][] createData() {

          patchfileName = "hi,how,are,you";
          patchsplit = patchfileName.split(",");

          Object[] arr = patchsplit ;

          System.out.println(arr.length);

          for(int i=0;i<arr.length;i++){
              System.out.println(arr[i].toString());
          }
          Object[][] data = new Object[arr.length][arr.length];

          for (int x = 0; x < arr.length; x++){
              data[x][x] = arr[x];

            }

          return data;

      } 



        @Test(dataProvider="getData")

        public void DownloadPatch(String patchfileNamea ){

            try{

            System.out.println("Name is b"+patchfileNamea);
            }
            catch (Exception e){
                org.testng.Assert.fail("Failed to Download Patch to NgDriver " + e.getMessage());

            } 
        }
}


TestNG] Running:
  C:\Users\Mohan Raj S\AppData\Local\Temp\testng-eclipse-1472908796\testng-customsuite.xml

4
hi
how
are
you
FAILED: DownloadPatch
org.testng.TestNGException: 
The data provider is trying to pass 4 parameters but the method testclasses.DtaProvider#DownloadPatch takes 1
    at org.testng.internal.Invoker.injectParameters(Invoker.java:1257)

请帮助我如何将参数顺序传递给我的@test方法?

2 个答案:

答案 0 :(得分:1)

错误日志中明确提到@Test方法只接受一个参数,而@DataProvider返回四个参数。

很简单,@ DataProvider返回的参数数量应该在@Test方法中传递。您的@Test方法应如下所示:

@Test(dataProvider="getData")
public void DownloadPatch(String param1, String param2, String param3, String param4){
   System.out.println(param1);
}

<强>更新:1

即使你有一些理由在@Test方法中只传递一个参数,你也需要以这种方式修改你的@DataProvider。

public Object[][] createData() {
    patchfileName = "hi,how,are,you";
    patchsplit = patchfileName.split(",");
    Object[][] data = new Object[patchsplit.length][1];
    for (int x = 0; x < patchsplit.length; x++) {
        data[x][0] = patchsplit[x];

    }
    return data;
}

答案 1 :(得分:0)

如果您知道要传递的参数,则可以使用以下参数将单个参数传递给@Test方法。

@DataProvider(name = "getData")
public Object[][] createData() {
    return new Object[][] { { "hi" }, { "how" }, { "are" }, { "you" } };
}