【问题标题】:How to write TestNG DataProvider annotation for Excel sheet with different colomun numbers for differnt rows如何为不同行的不同列号的 Excel 工作表编写 TestNG DataProvider 注释
【发布时间】:2016-09-29 06:56:54
【问题描述】:

我有一张excelsheet,数据如下

登录页面验证|
登录页面_登录 |用户名1 |密码1
登录页面_登录 |用户名2 |密码2
登录页面_登录 |用户名3 |密码3

我将“数组数组”返回给@Dataprovider 表单类读取 ExcelSheet(Excelutility.java)
有没有办法编写 @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); } }

【问题讨论】:

    标签: java arrays selenium selenium-webdriver testng-dataprovider


    【解决方案1】:

    如果您的 excel 表包含不同的列号,我们可以在读取 excel 表时进行处理,而不是在数据提供程序中处理它们。在您的代码中,替换以下部分

    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]);      
         }
      }
    }
    

    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]);      
        }
      }
    }
    

    如果我们使用getPhysicalNumberOfCells 方法而不是getLastCellNum,它将只返回包含数据的列数。因此,无需检查该列是否为空。

    希望这会有所帮助。

    【讨论】:

    • 在我的情况下,我能够处理 Excelutility 中的错误,但不能在 Testclass 中处理错误,因为当数组具有单个字符串并且测试方法采用 3 个字符串值时,Test 类中的“loginTest”方法抛出空指针异常如下@Test(dataProvider="access") public void loginTest(String testname,String username,String pwd) {} @DataProvider{public Object[][] access() {Object[][] testObjArray = ExcelUtils.getTableArray("Input.xlsx"); return (testObjArray);}
    • 能否请您粘贴完整的测试方法,以便我帮助您了解如何处理此异常
    • 在问题中添加了测试方法请检查,-谢谢
    • 你可以在testng中使用@Optional注解。将您的测试类修改为“public void AADLoginLogoutTest(String test,@Optional("") String username, @Optional("") String pwd) throws IOException {}”。如果没有向变量、用户名和密码传递值,则将采用空字符串。希望这会有所帮助
    • 也试过@optional,但没有运气。抛出 TestNGException:“数据提供者正在尝试传递 1 个参数,但方法测试。LoginLogoutTest#LoginLogout 需要 3 并且 TestNG 无法注入合适的对象”。
    【解决方案2】:

    我想你在 @DataProvider 方法中调用 getTableArray() 并且你在 getTableArray() 方法中得到 NullPointerException。您可以在 getTableArray() 中执行此操作,而不是在 @DataProvider 中处理该异常,因为这是读取 excel 工作表的所有操作。

    要了解在 getTableArray() 中处理异常的简单方法,您可以按照我的博客文章中给出的脚本-http://selenium-coding.blogspot.in/2016/05/generalized-apache-poi-script-for.html 它显示了阅读和编写 excelsheet 的更简单方法。它基本上将读取和写入 excel 表的代码放在一个类中,以便其他测试也可以使用它,并且它只在这些特定方法中完成异常处理。作为一种标准做法,我们应该让测试远离底层的复杂性(例如捕获异常等),以便让没有编写它们的人易于理解。

    【讨论】:

      【解决方案3】:

      重构你的代码,试试这个,它必须工作..

        /**
           * @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;
           }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多