2017-08-29 45 views
0

我已經創建了一個讀取一個包中的excel值的類,並且還有一個類以testng的形式檢查了不同類中的登錄。 我的ReadExcelFile.java是 包uat;如何給testng.xml中的路徑賦予動態值

public class ReadExcelFile extends BeforeAfterSuite{ 

    @Test 
    @Parameters("filename") 
    public void readXLSXFile(String fileName) { 
     InputStream XlsxFileToRead = null; 
     XSSFWorkbook workbook = null; 
     try { 
      XlsxFileToRead = new FileInputStream(fileName); 

      //Getting the workbook instance for xlsx file 
      workbook = new XSSFWorkbook(XlsxFileToRead); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     //getting the first sheet from the workbook using sheet name. 
     // We can also pass the index of the sheet which starts from '0'. 
     XSSFSheet sheet = workbook.getSheet("Sheet1"); 
     XSSFRow row; 
     XSSFCell cell; 

     //Iterating all the rows in the sheet 
     Iterator rows = sheet.rowIterator(); 

     while (rows.hasNext()) { 
      row = (XSSFRow) rows.next(); 

      //Iterating all the cells of the current row 
      Iterator cells = row.cellIterator(); 

      while (cells.hasNext()) { 
       cell = (XSSFCell) cells.next(); 

       if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { 
        System.out.print(cell.getStringCellValue() + " "); 
       } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { 
        System.out.print(cell.getNumericCellValue() + " "); 
       } else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) { 
        System.out.print(cell.getBooleanCellValue() + " "); 

       } 
      } 
      System.out.println(); 
      try { 
       XlsxFileToRead.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 



} 

和TestNG中我要傳遞的參數作爲文件名與路徑一起,但被硬編碼,而不是我想送動態值 因爲位置我打算以後此舉是共享的路徑。

回答

1

這裏是你如何做到這一點

  • 卸下@Parameters
  • 槓桿的依賴JVM參數說filename能夠選擇性地接受實際位置,如果沒有提供定義的JVM參數的默認值。

您的代碼可以像下面

@Test 
public void readXLSXFile() { 
    //To provide a different value for the excel sheet, use the JVM argument: -Dfilename 
    //For e.g., -Dfilename=src/test/resources/anotherdata.xls 
    //If this JVM argument is not provided, 
    //then the file name is defaulted to src/test/resources/data.xls 
    String fileName = System.getProperty("filename", "src/test/resources/data.xls"); 
    InputStream XlsxFileToRead = null; 
    XSSFWorkbook workbook = null; 
    //Rest of the code goes here 
} 
相關問題