0

Below is my code to retrieve the test data in the form of an object array to pass it to the dataprovider class. Can anyone please help me to find out why is my testData array is overwritten with the last value.

public class TestDataReader {

    XSSFWorkbook xlWorkbook = null;
    XSSFSheet sheet = null;
    XSSFRow row = null;
    XSSFCell cell = null;
    HashMap<Object, Object> testDataInEachRow = new HashMap<Object, Object>();
    String currentDir = Paths.get("").toAbsolutePath().toString();
    String testDataFileName = "\\TestData\\TestData.xlsx";
    String sheetName = null;

    String xlFilePath = currentDir + testDataFileName;

    public Object[][] readTestData(String sheetName) throws IOException {
        String rowHeader = null;
        String columnValue = null;
        FileInputStream fileInputStream = new FileInputStream(xlFilePath);
        xlWorkbook = new XSSFWorkbook(fileInputStream);
        sheet = xlWorkbook.getSheet(sheetName);
        int rowCount = sheet.getLastRowNum();
        Object[][] testData = new Object[rowCount][1]; // This object is created to store the MapData as an object for DataProvider
        

        if (sheet.getSheetName().equalsIgnoreCase(sheetName)) {
            for (int rowNum = 0; rowNum < rowCount; rowNum++) {
                row = sheet.getRow(rowNum + 1); // Since the first row will be header, parse from the second row
                int columnCount = row.getLastCellNum();
                for (int colNum = 0; colNum < columnCount; colNum++) {
                    rowHeader = sheet.getRow(0).getCell(colNum).toString();
                    if (row.getCell(colNum) != null) {
                        columnValue = row.getCell(colNum).toString();
                    } else {
                        columnValue = "";
                    }
                    testDataInEachRow.put(rowHeader, columnValue);
                }
                testData[rowNum][0] = testDataInEachRow;
            }
            System.out.println(testData[0][0]);
            System.out.println(testData[1][0]);
        }
        return testData;

    }
}
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
Vedavathi M
  • 1
  • 1
  • 2
  • 2
  • 2
    You create only one `testDataInEachRow` and continuously overwrite it. Instead of that you need to create a new `HashMap` for each row by writing `testDataInEachRow = new HashMap();` within the outer for loop (for example, after the line `int columnCount = row.getLastCellNum();` – Thomas Kläger Sep 23 '22 at 19:56

0 Answers0