简体   繁体   English

如何为不同行的不同列号的 Excel 工作表编写 TestNG DataProvider 注释

[英]How to write TestNG DataProvider annotation for Excel sheet with different column numbers for different rows

I have an Excel sheet with data as below我有一个 Excel 表,其中的数据如下

LoginPageValidation|            
LoginPage_login    | username1 | password1  
LoginPage_login    | username2 | password2   
LoginPage_login    | username3 | password3     

I am returning "array of arrays" to @Dataprovider form class reading ExcelSheet(Excelutility.java)我将“数组数组”返回给@Dataprovider表单类,读取 ExcelSheet(Excelutility.java)

Is there any way to write @DataProvider which handles nullpointerException while reading data from rows with single column data.有没有办法编写@DataProvider来处理 nullpointerException,同时从具有单列数据的行中读取数据。

public static Object[][] getTableArray() throws Exception 
{   
       String[][] tabArray = null;
       try {
           FileInputStream ExcelFile = new FileInputStream(FilePath);
           // Access the required test data sheet
           ExcelWBook = new XSSFWorkbook(ExcelFile);
           ExcelWSheet = ExcelWBook.getSheet(SheetName);
           int startRow = 0;
           int totalRows = ExcelWSheet.getLastRowNum()-ExcelWSheet.getFirstRowNum()+1;
           System.out.print("\nTOTAL ROWS "+totalRows+"\n");
    String a[][]=new String[totalRows][];
  for(int i=0;i<totalRows;i++)
  {
      int ColnumForRow=ExcelWSheet.getRow(i).getLastCellNum();
          a[i]=new String [ColnumForRow];
    for (int j=0;j<ExcelWSheet.getRow(i).getLastCellNum();j++)
    {
        if(getCellData(i,j).isEmpty())
        {System.out.println("\nEMPTY \n");}
        else
        { a[i][j]=getCellData(i,j);
          System.out.println("\nTABLE ARRAY : "+ a[i][j]);      
        }}
  }}
                return(tabArray);
        }

public static String getCellData(int RowNum, int ColNum) throws Exception 
    {try{   
             Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
            int dataType = Cell.getCellType();
            String CellData = Cell.getStringCellValue();
                return CellData;
            }
        }

} }

/ testClass / /测试类/
public class test1 { @Test(dataProvider="access") public void AADLoginLogoutTest(String test,String username,String pwd) throws IOException { System.out.println("CLAASS name AADLOGINLOGOUT"+this.getClass().getSimpleName()); } @DataProvider public Object[][] access() throws Exception { Object[][] testObjArray = ExcelUtils.getTableArray(); return (testObjArray); } }

refactored your code, try this, it must work..重构你的代码,试试这个,它必须工作..

  /**
     * @author revanthreddya
     *
     */
    package com.playground.excel;

    public class ExcelUtils 
    {
        private Workbook wb;
         private Sheet ws;

         public ExcelUtils(String file, String sheet) {
             try {

                   if (file.indexOf("xlsx") < 0) { 
                    wb = new HSSFWorkbook(new FileInputStream(new File(file)));
                    ws = wb.getSheet(sheet);
                   } else { 
                    wb = new XSSFWorkbook(new FileInputStream(new File(file)));
                    ws = (XSSFSheet) wb.getSheet(sheet);
                   }
                  } catch (IOException io) {
                   System.err.println("Invalid file '" + file
                     + "' or incorrect sheet '" + sheet
                     + "', enter a valid one");
                  }
        }


         public int rowCount(){
                return ws.getLastRowNum();
             }


         public String getCell(int rowIndex, int columnIndex) {
              Cell cell = null;

              try {
                cell = ws.getRow(rowIndex).getCell(columnIndex);
              } catch (Exception e) {
               System.err.println("The cell with row '" + rowIndex + "' and column '"
                 + columnIndex + "' doesn't exist in the sheet");
              }
              return new DataFormatter().formatCellValue(cell);
             }


    }



public class TestCase {

     @Test(dataProvider="access")
     public void AADLoginLogoutTest(String test, String username, String password) throws IOException 
     {
          System.out.println(" test :"+test+"  user "+username+"  password:"+  password); 
     }


     @DataProvider(name = "access")
     public Object[][] access() throws Exception {

      ExcelUtils userD= new ExcelUtils("input.xlsx", "Actions");

      ArrayList<Object> paraList = new ArrayList<Object>();

      int i = 1;
      int totalRows = userD.rowCount();
      System.out.println("TotalRows: "+totalRows);
      while (i < totalRows) {

       Object[] args = new Object[3];
       args[0] = userD.getCell(i, 0);
       args[1] = userD.getCell(i, 1);
       args[2] = userD.getCell(i, 2);

       paraList.add(args);

       i++;
      }

      Object[][] argsData = new Object[paraList.size()][];
      for (i = 0; i < paraList.size(); i++)
       argsData[i] = (Object[]) paraList.get(i);
      return argsData;
     }
}

If your excel sheet contains different column numbers, we can handle in reading the excel sheet rather than handling them in data provider.如果您的 excel 表包含不同的列号,我们可以在读取 excel 表时进行处理,而不是在数据提供程序中处理它们。 In your code, replace the below section在您的代码中,替换以下部分

for(int i=0;i<totalRows;i++)
{
  int ColnumForRow=ExcelWSheet.getRow(i).getLastCellNum();
  a[i]=new String [ColnumForRow];
  for (int j=0;j<ExcelWSheet.getRow(i).getLastCellNum();j++)
  {
     if(getCellData(i,j).isEmpty())
     { 
       System.out.println("\nEMPTY \n");
     }
     else
     { 
       a[i][j]=getCellData(i,j);
       System.out.println("\nTABLE ARRAY : "+ a[i][j]);      
     }
  }
}

with

for(int i=0;i<totalRows;i++)
{
  int ColnumForRow=ExcelWSheet.getRow(i).getPhysicalNumberOfCells();
  a[i]=new String [ColnumForRow];
  for (int j=0;j<ColnumForRow;j++)
  {
    if(getCellData(i,j).isEmpty())
    { 
       System.out.println("\nEMPTY \n");
    }
    else
    { 
       a[i][j]=getCellData(i,j);
       System.out.println("\nTABLE ARRAY : "+ a[i][j]);      
    }
  }
}

if we use getPhysicalNumberOfCells method instead of getLastCellNum it will return only the column count with data.如果我们使用getPhysicalNumberOfCells方法而不是getLastCellNum它将只返回包含数据的列数。 Hence there would be no need to check whether the column is empty or not.因此,无需检查该列是否为空。

Hope this helps.希望这可以帮助。

I suppose you are calling getTableArray() in @DataProvider method and you are getting NullPointerException in getTableArray() method.我想你在 @DataProvider 方法中调用 getTableArray() 并且你在 getTableArray() 方法中得到 NullPointerException 。 Rather than handling that exception in @DataProvider, you can do that in getTableArray() as that is where all action of reading of excel sheet is going on.您可以在 getTableArray() 中执行此操作,而不是在 @DataProvider 中处理该异常,因为这是读取 excel 工作表的所有操作的地方。

To know a simple way of handling the exception in getTableArray(), you can follow the script as given in my blog post- http://selenium-coding.blogspot.in/2016/05/generalized-apache-poi-script-for.html It shows easier way to go about reading and writing excelsheet.要了解在 getTableArray() 中处理异常的简单方法,您可以按照我的博客文章中给出的脚本进行操作 - http://selenium-coding.blogspot.in/2016/05/generalized-apache-poi-script- for.html它显示了阅读和编写 excelsheet 的更简单方法。 It basically puts the code that reads and writes the excel sheet in one class so that it can be used by other tests as well and it does the exception handling done in those particular methods only.它基本上将读取和写入 excel 表的代码放在一个类中,以便其他测试也可以使用它,并且它只在这些特定方法中完成异常处理。 As a standard practice, we should keep the tests away from the underlying complexities (such as catching the exception and etc) so that they become simple to understand by someone who has not written them.作为一种标准做法,我们应该让测试远离底层的复杂性(例如捕获异常等),以便让没有编写它们的人能够简单地理解它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在testNG中使用@dataprovider从excel读取不同的数据类型 - How can I read different datatypes from excel using @dataprovider in testNG 如何使用Apache POI和TestNG dataProvider编写Excel - How to write excel using Apache POI with TestNG dataProvider 使用TestNG DataProvider时,是否可以从SAME Excel工作表中读取和写入参数? - When using TestNG DataProvider is there a way to read and write parameters from the SAME Excel sheet? 在testng中使用不同的dataprovider运行相同的测试 - running same test with different dataprovider in testng 如何使用Selenium WebDriver将3个不同变量中的3列值写入Excel工作表 - How to write the 3 column values in 3 different variables into an Excel sheet using selenium webdriver 如何配置NatTable FilterComboBox以为每列提供不同的DataProvider - How to configure NatTable FilterComboBox to have a different DataProvider for each column 访问不同类的测试注释中的值-TestNg - Accessing values in annotation of a test in a different class - TestNg 为什么@DataProvider注释在TestNG中的@BeforeClass之前运行? - Why is @DataProvider annotation runs before @BeforeClass in TestNG? 在新的Excel工作表中写行 - Write rows in a new excel sheet 如何使用Java for Selenium WebDriver在一个Excel工作表中编写2种不同的结果 - How to write the 2 different results in one excel sheet using java for selenium webdriver
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM