【问题标题】:Pass Excel value into multiple methods of same class将 Excel 值传递给同一类的多个方法
【发布时间】:2020-07-09 04:33:10
【问题描述】:

我正在使用 selenium 和 Java 来创建我的自动化脚本。我需要你们所有人的帮助。

我有一个包含 5 列的 excel - 比如说名称是 Col1 、 Col2 、 Col3 、 Col4 、 Col5。

我有课。

public class testone{

    @Test(Dataprovider="test")
      public void methodone(String Col1) {
      }

    @Test(Dataprovider="test")
      public void methodtwo(String Col2, String Col3){
    }

    @Test(Dataprovider="test")
     public void methodthree(String Col4, String Col5){
    }

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

        String sheetName = "headercomptests";
        int rows = excel.getRowCount(sheetName);
        int cols = excel.getColumnCount(sheetName);
        Object[][] data = new Object[rows - 1][cols];
        for (int rowNum = 2; rowNum <= rows; rowNum++) { 
                for (int colNum = 0; colNum < cols; colNum++) {
                                data[rowNum - 2][colNum] = excel.getCellData(sheetName, colNum,    rowNum);     }       }
       return data; } //end of dataprovider class 

现在它会在所有方法中引发错误,因为列数与参数不匹配。如前所述,我怎样才能得到它。

如果参数个数与 excel cols 匹配,则有效。

谢谢。

【问题讨论】:

    标签: excel selenium selenium-webdriver testng testng-dataprovider


    【解决方案1】:

    不要使您的代码过于复杂。由于您的测试需要不同数据,请使用两个不同数据提供者。每种测试方法一个。每个数据提供者都会提供自己的一组列。

    【讨论】:

      【解决方案2】:

      您可以在@DataProvider 和@Test 方法中使用HashMap。

      1. 更新DataProvider 以返回HashMap

        @DataProvider(name="test")
        public Object[][] getData() {    
        Object[][] data = new Object[rows - 1][cols];
        
         for (int rowNum = 2; rowNum <= rows; rowNum++) 
         { 
           // Create Hashmap after every row iteration
           HashMap<Object, Object> testData = new HashMap<Object, Object>();
           for (int colNum = 0; colNum < cols; colNum++) 
           {
            //Assuming excel sheet has Col1 , Col2 , Col3 , Col4, Col5 as name in 1st row
             testData.put(excel.getCellData(sheetName, colNum, 0),excel.getCellData(sheetName, colNum, rowNum));     
           }
           // Add every row in hashmap
           data[r][0] = testData;   
         }
         return data; 
        }
        

      请按照 excel 表更新上述代码,以便与 HashMap 正确映射

      1. 通过传递HashMap 作为参数更新所有@Test 方法,然后在每个@Test 方法中,根据要求检索列值:

        @Test(Dataprovider="test")
        public void methodone(Map<Object, Object> testData) {
         //Get value of column 'col1' from testData HashMap
         String Col1 = (String)testData.get("Col1");
        }
        

      【讨论】:

        猜你喜欢
        • 2012-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-19
        • 2017-07-21
        • 2012-11-07
        • 1970-01-01
        相关资源
        最近更新 更多