TestNG:使用Dataprovider迭代数组

时间:2014-02-25 17:32:54

标签: java selenium-webdriver testng jxl

我正在使用Selenium Webdriver进行自动化测试,此代码适用于TestNg dataprovider,摘要:我将数据从Excel工作表传输到数据, 它工作正常。当我调试代码时,我将TestData作为testGoogle1(String search1, String Search2)进行第一次迭代Search1 = Webdriver, Search2 = Qtp, so on,,,, 我想要的是它应该直接返回像testGoogle1(String search[])这样的值数组,这样在@Test本身我可以添加我的函数迭代所有的行和列并测试它们。

任何人都可以请你知道如何写它。

测试数据表

Test Data

这是我的代码

package ExcelTest;
import com.thoughtworks.selenium.*;
import static org.testng.AssertJUnit.*;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;   
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;   
import org.testng.annotations.AfterTest;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import jxl.*;


public class Sample{

      WebDriver driver;

        @BeforeTest
        public void startTest(){
            driver = Startup.basic();
        } 


@DataProvider(name = "DP1")
public Object[][] createData1() throws Exception{
     Object[][] retObjArr=getTableArray("G:\\Selenium Jar Files\\TestData\\Data.xls","DataPool");
    return(retObjArr);

}

@Test (dataProvider = "DP1")
public void testGoogle1(String search1, String Search2) throws Exception{
//selenium.open("http://www.google.co.in/");
//  driver.get("http://www.google.co.in/");

    //String hello = search.length;
//for(int i=0; i< search.length ;i++)
//{
System.out.println("param   " +search);
Thread.sleep(3000);
System.out.println("Opened");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys(search);
element.submit();
System.out.println("Clicked");
}
//}

@AfterClass
public void tearDown() throws Exception {
//selenium.stop();
}


public String[][] getTableArray(String xlFilePath,String sheetName) throws Exception{

    String[][] tabArray=null;


      File inputWorkbook = new File(xlFilePath);
        Workbook w;
        int startRow,startCol, endRow, endCol,ci,cj;
        try {
            //w = Workbook.
            w = Workbook.getWorkbook(inputWorkbook);
            // Get the first sheet
            Sheet sheet = w.getSheet(sheetName);
            // Loop over first 10 column and lines
            endRow = sheet.getRows();
            endCol = sheet.getColumns();
            tabArray=new String[endRow-1][endCol-1];

            ci=0;

            for (int i=1;i<endRow;i++,ci++){
                cj=0;
                for (int j=1;j<endCol;j++,cj++){

                  Cell cell = sheet.getCell(j, i);
                tabArray[ci][cj] = cell.getContents(); 

                }
            //    System.out.println("");
            }
            //file.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }




       return(tabArray);
    }

}

任何人都可以分享任何想法吗? 感谢

编辑代码:

public class Sample{

      WebDriver driver;

        @BeforeTest
        public void startTest(){
            driver = Startup.basic();
        } 


@DataProvider(name = "DP1")
public Object[][][] createData1() throws Exception{
     Object[][][] retObjArr=getTableArray("G:\\Selenium Jar Files\\TestData\\Data.xls","DataPool");
    return (retObjArr);

}

@Test (dataProvider = "DP1")
public void testGoogle1(String search, String het) throws Exception{

System.out.println("param   " +search);
Thread.sleep(3000);
System.out.println("Opened");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys(search);
element.submit();
System.out.println("Clicked");
}
//}

@AfterClass
public void tearDown() throws Exception {
//selenium.stop();
}


public Object[][][] getTableArray(String xlFilePath,String sheetName) throws Exception{

    Object[][] tabArray=null;


      File inputWorkbook = new File(xlFilePath);
        Workbook w;
        int startRow,startCol, endRow, endCol,ci,cj,ck;
        try {
            //w = Workbook.
            w = Workbook.getWorkbook(inputWorkbook);
            // Get the first sheet
            Sheet sheet = w.getSheet(sheetName);
            // Loop over first 10 column and lines
            endRow = sheet.getRows();
            endCol = sheet.getColumns();
            tabArray=new String[endRow-1][endCol-1];

            ci=0;

            for (int i=1;i<endRow;i++,ci++){
                cj=0;

                for (int j=1;j<endCol;j++,cj++){

                  Cell cell = sheet.getCell(j, i);
                tabArray[ci][cj] = cell.getContents(); 

                }
            //    System.out.println("");
            }
            //file.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }



       return(tabArray);  /// Here Getting the error **Type mismatch: cannot convert from Object[][] to Object[][][]**
    }

}

4 个答案:

答案 0 :(得分:0)

这是@DataProvider的工作方式,假设我有以下数组:

[[value1, value2],
 [value3, value4],
 [value5, value6]]

请注意,有3行2列。测试将运行3次,每次传递2个值。它的价值并不重要。

现在,如果您希望测试只运行一次,那么您的数组应如下所示:

[[value1]]

我们可以使value1成为我们想要的任何东西,所以如果value1是上面的数组,那么它会将整个数组传递给dataProvider。因此,您的return语句应返回{{tabArray}}

答案 1 :(得分:0)

查看代码,您正在尝试创建一个返回Object [] [] []的dataprovider函数。你不能这样做; dataprovider函数必须返回Object [] [](任何Object的二维数组),或者Iterator,它将以稍微不同的方式执行相同的功能。

你当然可以在返回的2D数组中嵌套另一个数组;这就是为什么它是Object [] []而不是特定类型。

还要确保正确构建返回结果。例如,您不能执行以下操作,因为它不构造Object [] []数组:

return {{myArray}};

相反,你会这样做:

return new Object[][]{{myArray}};

答案 2 :(得分:0)

我认为jxl比它需要的更难。我使用reading Excel data(最近成为一个完整的Apache项目)编写了一个TestNG DataProvider Apache MetaModel的示例,您可以找到here

public static Object[][] getCsvData( File csvFile ) 
    {   
        CsvConfiguration conf = new CsvConfiguration( 1 );
        DataContext csvContext = DataContextFactory.createCsvDataContext( csvFile, conf );
        Schema schema = csvContext.getDefaultSchema();
        Table[] tables = schema.getTables();
        Table table = tables[0]; // a representation of the csv file name including extension
        DataSet dataSet = csvContext.query()
                .from( table )
                .selectAll()
                .where("run").eq("Y")
                .execute();
        List<Row> rows = dataSet.toRows();
        Object[][] myArray = get2ArgArrayFromRows( rows );
        return myArray;
    }

第二部分:

public static Object[][] get2ArgArrayFromRows( List<Row> rows ) {
        Object[][] myArray = new Object[rows.size()][2];
        int i = 0;
        SelectItem[] cols = rows.get(0).getSelectItems();
        for ( Row r : rows ) {
            Object[] data = r.getValues();
            for ( int j = 0; j < cols.length; j++ ) {
                if ( data[j] == null ) data[j] = ""; // force empty string where there are NULL values
            }
            myArray[i][0] = cols;
            myArray[i][1] = data;
            i++;
        }
        logger.info( "Row count: " + rows.size() );
        logger.info( "Column names: " + Arrays.toString( cols ) );
        return myArray;
    }

使用此DataProvider的测试示例:

@Test( dataProvider = "csv" )
public void testPrintCsvRowToLog( SelectItem[] cols, Object[] data ) {
    String theCols = Joiner.on("|").join( cols );
    String aRow = Joiner.on("|").join( data );
    logger.info( theCols ); 
    logger.info( aRow ); 
}

答案 3 :(得分:0)

您不能将TestNg参数和Dataprovider用于@Test注释。

更好地将DataProvider注释用于BeforeTest / Beforeclass注释,并将@Parameter注释用于@Test注释