Importing data from Excel and passing it to the method
To start, each set of data should be placed on its own Excel sheet.
https://i.sstatic.net/ZJFqE.png
Sheet name: Dataset1
Column name: Column1
The values in the column (excluding the column name) are extracted for use. TestNG then iterates through this data in the test method.
The next step involves fetching the data from Excel.
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class BaseTestProvider {
Object[][] dataSupplierBase(String path, String sheetname) throws IOException {
File file = new File(path); //Name of the FILE
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet(sheetname);//Name of the SHEET
wb.close();
int lastRowNum = sheet.getLastRowNum();
int lastCellNum = sheet.getRow(0).getLastCellNum();
Object[][] obj = new Object[lastRowNum][1];
for (int i = 0; i < lastRowNum; i++) {
Map<Object, Object> datamap = new HashMap<>();
for (int j = 0; j < lastCellNum; j++) {
datamap.put(sheet.getRow(0).getCell(j).getStringCellValue(), sheet.getRow(i + 1).getCell(j).getStringCellValue());
}
obj[i][0] = datamap;
}
return obj;
}
}
The third part involves setting up TestNG's data provider.
public class TestCaseDataProvider extends BaseTestProvider {
@DataProvider(name = "test1")
public Object[][] dataSupplier1() throws IOException {
String sheetname = "Dataset1";
return dataSupplierBase("path to excel file", sheetname);
}
Afterwards, utilize maps to extract data from specific sheets and columns.
@Test(dataProvider = "test1", dataProviderClass = TestCaseDataProvider.class)
public void testMethod(Map<Object, Object> map) {
System.out.println(String.valueOf(map.get("Column1")));
}
By changing the data provider name manually or via code, you can seamlessly switch between different datasets.
Unresolved: Collating all columns at once and manipulating rows.