How can I run Same Test Case Multiple Times with Different Set of Data using TestNG + Selenium WebDriver

33 views Asked by At

I have one utility class as DataManager.java where I have written a method to read data from an excel sheet.

public static XSSFWorkbook xssfWorkbook;
public static XSSFSheet xssfSheet;

public static Object[][] readUserCredentials(String sheetName) {//return table data(2 dimensional object array)

try {
FileInputStream file = new FileInputStream(System.getProperty("user.dir") + "/TestData/Data.xlsx");
xssfWorkbook = new XSSFWorkbook(file);
xssfSheet = xssfWorkbook.getSheet(sheetName);
int totalRows = xssfSheet.getLastRowNum();
int totalCols = xssfSheet.getRow(1).getLastCellNum();

Object[][] data = new Object[xssfSheet.getLastRowNum()][xssfSheet.getRow(0).getLastCellNum()];
for (int r = 0; r < totalRows; r++) {
for (int c = 0; c < totalCols; c++) {
data[r][c] = xssfSheet.getRow(r + 1).getCell(c).toString();
 }
 }
xssfWorkbook.close();
file.close();
return data;

} catch (IOException e) {
        throw new RuntimeException(e);
}

}

My test case is in Tests package -> Login package -> LoginTest.java

@Test(dataProvider = "LoginCredentials")
public void Login(String email, String password){
LandingPage landingPage = new LandingPage();
landingPage.goToWebCentral();
LoginPage loginPage = new LoginPage();
loginPage.typeEmail(email);
loginPage.typePassword(password);

}

@DataProvider(name = "LoginCredentials")
public Object[][] getData(){
Object[][]loginData =  DataManager.readUserCredentials("Login");
return loginData;
}

This gives a NullPointerException and it does not run the test case multiple times. Reading data part works properly.

How can I run the same test case with mltiple data in an excel by reading the excel, get email and password, enter credentials to login to account

1

There are 1 answers

0
Nivasha Pathirana On

I fixed the issue by adding @BeforeMethod annotation instead of @BeforeClass as @BeforeMethod is invoked before execution of each test method and @BeforeClass annotation is invoked only once before starting all test cases.

https://www.javatpoint.com/testng-beforemethod-annotation