Chuyển tới nội dung
Home » Data Driven In Selenium | Similar Articles

Data Driven In Selenium | Similar Articles

Selenium Framework Tutorial #9 - Data Driven Testing with TestNG DataProvider

How to create a Data Driven Framework in Selenium using Apache POI?

We have learned in the previous article “Read & Write Data from Excel in Selenium” how to read and write data in Excel files using Apache POI and then pass the same data sets as test data to the Selenium tests. But in that script, all the actions of reading data from an Excel file, writing data to the Excel file, passing the data to the Selenium actions were happening in the main method of the class. That format is acceptable if we are just writing one or two test cases. However, when we have to develop an automation framework that will have multiple test scenarios, then it should properly organize and should have a defined folder hierarchy.

A basic thumb rule for the data driven testing framework would be to segregate the test data from the test scripts. Also, the actions to read/write the data from files should segregate and be available as utilities.

Follow the steps as mentioned below to create a basic Data Driven framework, which will be used to automate the “Student Registration Form”.

  • Create three New Packages in your Project for testCases, testData, and utilities.
  • Under the testData package, put your Excel Sheet that has test data. Using this, we separate the test data from the testCases.
  • Under the utilities, create a New Class and name it “ExcelUtils”. It will contain all functions related to Excel used for reading and writing.
  • Under the utilities package, create another class “Constants”. It will contain the constant values across the framework like testdata file path, URL of the application, etc.
  • Under the testCases package, we will create the test files that contain the Selenium code for interacting with web elements. (For Example, RegisterStudentTest.java)

After performing the above steps, the folder structure will look like:

Let’s understand the details of each of these classes:

  1. ExcelUtils Class – It is a utility class that will contain all the methods related to Excel Sheet read and write operations along with initializing the Workbook. You can then reuse the methods in different test cases, by creating an object of Excel Utils Class. The code for this class will be as below –


package utilities; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ExcelUtils { private static HSSFWorkbook workbook; private static HSSFSheet sheet; private static HSSFRow row; private static HSSFCell cell; public void setExcelFile(String excelFilePath,String sheetName) throws IOException { //Create an object of File class to open xls file File file = new File(excelFilePath); //Create an object of FileInputStream class to read excel file FileInputStream inputStream = new FileInputStream(file); //creating workbook instance that refers to .xls file workbook=new HSSFWorkbook(inputStream); //creating a Sheet object sheet=workbook.getSheet(sheetName); } public String getCellData(int rowNumber,int cellNumber){ //getting the cell value from rowNumber and cell Number cell =sheet.getRow(rowNumber).getCell(cellNumber); //returning the cell value as string return cell.getStringCellValue(); } public int getRowCountInSheet(){ int rowcount = sheet.getLastRowNum()-sheet.getFirstRowNum(); return rowcount; } public void setCellValue(int rowNum,int cellNum,String cellValue,String excelFilePath) throws IOException { //creating a new cell in row and setting value to it sheet.getRow(rowNum).createCell(cellNum).setCellValue(cellValue); FileOutputStream outputStream = new FileOutputStream(excelFilePath); workbook.write(outputStream); } }

The above code contains different methods like setExcelFile to initialize the Excel Workbook, getCellValue to retrieve the value present in a particular cell in the file, setCellValue to set some value into a newly created cell. In a similar way, you can create different methods related to excel operations in this class.

  1. Constants Class- It is used to put constant values in a file so that the same can be reused across test cases. One more advantage of placing values in separate files is that since these values are common across various tests if there is any change in any of the values, you will just have to update in one place. For example, if the file path is changed, then instead of updating all the test cases with the new value, you can just update it here in one file. The structure and values present in this class are as below –


package utilities; public class Constants { public static final String URL = "https://demoqa.com/automation-practice-form"; public static final String Path_TestData = "E:\\Projects\\src\\testData\\"; public static final String File_TestData = "TestData.xls"; }

  1. RegisterStudentTest- It is the test script for the student registration form, which we used to enter the first name, last name, mobile, email, gender, etc for a particular student. Since we have now separated the excel related methods in a separate file, the code of our test case also changes.

We will create an object of ExcelUtils class in this test file and also use Constants to refer to the path of the file.

The updated code now looks like –


package testCases; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import utilities.Constants; import utilities.ExcelUtils; import java.io.IOException; import java.util.concurrent.TimeUnit; public class RegisterStudentTest { //creating object of ExcelUtils class static ExcelUtils excelUtils = new ExcelUtils(); //using the Constants class values for excel file path static String excelFilePath =Constants.Path_TestData+Constants.File_TestData; public static void main(String args[]) throws IOException { //set the Chrome Driver path System.setProperty("webdriver.chrome.driver","E:\\Projects\\chromedriver.exe"); //Creating an object of ChromeDriver WebDriver driver = new ChromeDriver(); //launching the specified URL driver.get("https://demoqa.com/automation-practice-form"); //Identify the WebElements for the student registration form WebElement firstName=driver.findElement(By.id("firstName")); WebElement lastName=driver.findElement(By.id("lastName")); WebElement email=driver.findElement(By.id("userEmail")); WebElement genderMale= driver.findElement(By.id("gender-radio-1")); WebElement mobile=driver.findElement(By.id("userNumber")); WebElement address=driver.findElement(By.id("currentAddress")); WebElement submitBtn=driver.findElement(By.id("submit")); //calling the ExcelUtils class method to initialise the workbook and sheet excelUtils.setExcelFile(excelFilePath,"STUDENT_DATA"); //iterate over all the row to print the data present in each cell. for(int i=1;i<=excelUtils.getRowCountInSheet();i++) { //Enter the values read from Excel in firstname,lastname,mobile,email,address firstName.sendKeys(excelUtils.getCellData(i,0)); lastName.sendKeys(excelUtils.getCellData(i,1)); email.sendKeys(excelUtils.getCellData(i,2)); mobile.sendKeys(excelUtils.getCellData(i,3)); address.sendKeys(excelUtils.getCellData(i,4)); //Click on the gender radio button using javascript JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", genderMale); //Click on submit button submitBtn.click(); //Verify the confirmation message WebElement confirmationMessage = driver.findElement(By.xpath("//div[text()='Thanks for submitting the form']")); //check if confirmation message is displayed if (confirmationMessage.isDisplayed()) { // if the message is displayed , write PASS in the excel sheet using the method of ExcelUtils excelUtils.setCellValue(i,6,"PASS",excelFilePath); } else { //if the message is not displayed , write FAIL in the excel sheet using the method of ExcelUtils excelUtils.setCellValue(i,6,"FAIL",excelFilePath); } //close the confirmation popup WebElement closebtn=driver.findElement(By.id("closeLargeModal")); closebtn.click(); //wait for page to come back to registration page after close button is clicked driver.manage().timeouts().implicitlyWait(2000,TimeUnit.SECONDS); } //closing the driver driver.quit(); } }

The above class will perform the actions on the student registration page. However, if you notice, methods of the ExcelUtils handle all the excel related code.

So, this is one of the ways you can use the data driven framework in Selenium. Additionally, you can utilize the advantage of running the same test across multiple sets of data.

Key Takeaways

  • Data-driven is a test automation framework that stores test data in a table or spread spreadsheet format.
  • Additionally, a Data-driven Testing framework helps to separate test data from Functional tests. Moreover, it allows testing applications with multiple sets of data values without rewriting the same code across different test scripts.
  • Also, we perform data-driven Testing in Selenium using Apache POI. It is a library that helps to read and write data in the Excel Sheet.

Similar Articles

Data-Driven Testing Guide With Selenium And Katalon

Working as a software tester, are you sometimes tired of the repetitive and time-consuming nature of the whole process? If yes, a data-driven framework is exactly what you need.

A data-driven framework in Selenium is an approach to automated testing that separates test scripts from test data, enabling testers to run the same test script with different data inputs. It involves storing test data in external sources like spreadsheets or databases and dynamically feeding this data into Selenium scripts during test execution.

Why is this significant? Imagine effortlessly testing your application across various user inputs, browsers, and platforms, all while reducing maintenance efforts. Data-driven frameworks make data-driven testing a breeze, saving you time and resources, and ultimately enhancing the quality of your software. Say goodbye to repetitive testing and hello to streamlined, data-powered success!

In this article, we’ll explain the concept of a data-driven framework in-depth and then provide you with the code for such a framework in Selenium.

Selenium Framework Tutorial #9 - Data Driven Testing with TestNG DataProvider
Selenium Framework Tutorial #9 – Data Driven Testing with TestNG DataProvider

Data-driven testing framework in Selenium

Selenium can be used to create a data-driven testing framework. Leveraging Selenium, you can create the backbone for efficient and scalable data-driven testing, enabling your team to seamlessly manage test data, thereby enhancing the reliability and maintainability of automated tests.

The key components of this framework include:

  • Test script: Test scripts are the core of the automation process and should be designed to be reusable and independent of specific data values. Specifically, these are the Selenium WebDriver scripts that interact with the web application under test.
  • Test data: Test data includes the input values, expected results, and any other data required for test execution. This is the dynamic element of the framework and can be stored in various formats, including CSV files, Excel spreadsheets, or databases. Each row in the data source represents a unique set of inputs for your test script.
  • Parameterization: Test data is fed into the test script as parameters. These parameters replace the hard-coded values in the script, allowing it to adapt to different scenarios. To illustrate, if you are testing a login page, parameters could include usernames and passwords.
  • Reporting and logging: To monitor and report the test execution, comprehensive logging and reporting mechanisms are required, which can help in tracking test execution, identifying failures, and generating meaningful reports for analysis.

Overall, a data-driven framework enhances test automation. Whether you’re testing web applications, APIs, or mobile apps, mastering the data-driven framework will undoubtedly elevate your Selenium test automation game.

Read More: 6 Common Types of Software Test Automation Frameworks

How To Create a Data-Driven Framework in Selenium Using Apache POI

Apache POI is an open-source Java library designed to help developers work with Microsoft Office file formats such as Excel, Word, and even PowerPoint documents. It enables you to interact with data sets, and when paired with Selenium, an automation testing framework, you can easily create data-driven test cases that can both read data, automate web interactions, and generate test reports.

Step 1: Download your IDE

First, you need to set up your development environment for creating and running Selenium automation tests. You can use popular Java IDEs like Eclipse and IntelliJ, and then, in their starting interface, you can navigate to File > New > Project to set up a new project.

Make sure to also download the JAR files for Selenium WebDriver here and Apache POI libraries here.

Step 2: Install the libraries

In Eclipse:

  1. Right-click on your project in the Project Explorer.
  2. Select “Build Path” > “Configure Build Path.”
  3. In the “Libraries” tab, click on the “Add External JARs” button.
  4. Browse to the location where you saved the downloaded JAR files and add them to your project.
  5. Click “Apply” and then “OK” to save the changes.

In IntelliJ IDEA:

  1. Right-click on your project in the Project Explorer.
  2. Select “Open Module Settings” or “Add Framework Support,” depending on your IntelliJ version.
  3. In the “Libraries” tab, click the “+” button to add JARs or directories.
  4. Select the JAR files you downloaded, and IntelliJ will add them to your project.

You are now ready to use Selenium WebDriver to automate web tests and Apache POI to work with Excel files in your project.

Step 3: Create a test data Excel file

Simply prepare your test data in a spreadsheet. Each row represents a different test case, and the data in each column corresponds to the parameters you want to pass to your test cases. To know what type of data you should populate your sheet with, it is recommended to write out your test plan and test strategy document first. They give you a comprehensive view over your testing objectives.

Step 4: Create a data-driven test script

Once it’s already, you can write your Selenium test script to automate your test cases, but instead of hard-coding the test data, you can read it from the Excel file you prepared. To do it, you need to initiate a Workbook and Sheet object to read data.

Here’s an example of a test script written in Java using Selenium and Apache POI to test the login feature. Let’s assume that you have a ‘username’ and ‘password’ field in your XLSX file called “data.xlsx”, and the site you want to test the login feature is called “https://testwebsite.com”:


import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class DataDrivenTest { public static void main(String[] args) throws IOException { // Initialize WebDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); // Initialize Excel file FileInputStream file = new FileInputStream(new File("path/to/your/excel/data.xlsx")); Workbook workbook = new XSSFWorkbook(file); Sheet sheet = workbook.getSheet("Sheet1"); // Iterate through the rows and columns to read the data for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); String username = row.getCell(0).getStringCellValue(); String password = row.getCell(1).getStringCellValue(); // Execute the test with the current set of data driver.get("https://testwebsite.com"); WebElement usernameField = driver.findElement(By.id("username")); WebElement passwordField = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("login-button")); usernameField.sendKeys(username); passwordField.sendKeys(password); loginButton.click(); // Add verification/assertion steps here // Close the browser or perform any necessary cleanup } file.close(); driver.quit(); } }

However, please note that the previous script did not include a test reporting mechanism. To enable test logging, you need to import the java.util.logging package. Here’s the updated version for test logging mechanism:


import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class DataDrivenTest { public static void main(String[] args) throws IOException { // Initialize WebDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); // Initialize logging Logger logger = Logger.getLogger(DataDrivenTest.class.getName()); FileHandler fileHandler = new FileHandler("test_report.log"); logger.addHandler(fileHandler); // Initialize Excel file FileInputStream file = new FileInputStream(new File("path/to/your/excel/data.xlsx")); Workbook workbook = new XSSFWorkbook(file); Sheet sheet = workbook.getSheet("Sheet1"); // Iterate through the rows and columns to read the data for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); String username = row.getCell(0).getStringCellValue(); String password = row.getCell(1).getStringCellValue(); // Execute the test with the current set of data driver.get("https://testwebsite.com"); WebElement usernameField = driver.findElement(By.id("username")); WebElement passwordField = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("login-button")); usernameField.sendKeys(username); passwordField.sendKeys(password); loginButton.click(); // Add verification/assertion steps here // Example: You can check the URL, page title, or specific elements for expected conditions. if (driver.getCurrentUrl().equals("https://testwebsite.com/dashboard")) { logger.log(Level.INFO, "Test case PASSED: Username=" + username + ", Password=" + password); } else { logger.log(Level.SEVERE, "Test case FAILED: Username=" + username + ", Password=" + password); } // Close the browser or perform any necessary cleanup } file.close(); driver.quit(); } }

Apache POI Tutorial Part10 - Data Driven Testing in Selenium | TestNG DataProvider and Excel
Apache POI Tutorial Part10 – Data Driven Testing in Selenium | TestNG DataProvider and Excel

Data Driven Testing là gì?

Data-driven là một framework của kiểm thử tự động nơi mà lưu trữ dữ liệu trong một bảng hoặc các bảng tính.Các kiểm thử viên chỉ việc viết một kịch bản kiểm thử nhưng vẫn có thể chạy trên các bộ dữ liệu test khác nhau.Trong framework này các dữ liệu được lấy vào từ f nhiều ile lưu trữ( có thể là file XLSX, XML, CSV, database) và được lưu lại tại các biến của kịch bản test.
https://images.viblo.asia/3f9f5a20-96f4-4f7c-bd5d-80b24e03e80c.png

Data Driven Framework in Selenium

Data Driven Framework in Selenium is a method of separating data sets from the test case. Once the data sets are separated from the test case, it can be easily modified for a specific functionality without changing the code. It is used to fetch test cases and suites from external files like Excel, .csv, .xml or some database tables.

To read or write an Excel, Apache provides a very famous library POI. This library is capable enough to read and write both XLS and XLSX file format of Excel.

To read XLS files, an HSSF implementation is provided by POI library.

To read XLSX, XSSF implementation of POI library will be the choice. Let’s study these implementations in detail.

We already learned about Data Driven Testing in our previous tutorial

Ngobrolin Open Source - Ngobrolin WEB
Ngobrolin Open Source – Ngobrolin WEB

Best practices of Data Driven testing:

Below given are Best testing practices for Data-Driven testing:

  • It is ideal to use realistic information during the data-driven testing process
  • Test flow navigation should be coded inside the test script
  • Drive virtual APIs with meaningful data
  • Use Data to Drive Dynamic Assertions
  • Test positive as well as negative outcomes
  • Repurpose Data Driven Functional Tests for Security and Performance

How To Create a Data-Driven Framework in Selenium Using Apache POI

Apache POI is an open-source Java library designed to help developers work with Microsoft Office file formats such as Excel, Word, and even PowerPoint documents. It enables you to interact with data sets, and when paired with Selenium, an automation testing framework, you can easily create data-driven test cases that can both read data, automate web interactions, and generate test reports.

Step 1: Download your IDE

First, you need to set up your development environment for creating and running Selenium automation tests. You can use popular Java IDEs like Eclipse and IntelliJ, and then, in their starting interface, you can navigate to File > New > Project to set up a new project.

Make sure to also download the JAR files for Selenium WebDriver here and Apache POI libraries here.

Step 2: Install the libraries

In Eclipse:

  1. Right-click on your project in the Project Explorer.
  2. Select “Build Path” > “Configure Build Path.”
  3. In the “Libraries” tab, click on the “Add External JARs” button.
  4. Browse to the location where you saved the downloaded JAR files and add them to your project.
  5. Click “Apply” and then “OK” to save the changes.

In IntelliJ IDEA:

  1. Right-click on your project in the Project Explorer.
  2. Select “Open Module Settings” or “Add Framework Support,” depending on your IntelliJ version.
  3. In the “Libraries” tab, click the “+” button to add JARs or directories.
  4. Select the JAR files you downloaded, and IntelliJ will add them to your project.

You are now ready to use Selenium WebDriver to automate web tests and Apache POI to work with Excel files in your project.

Step 3: Create a test data Excel file

Simply prepare your test data in a spreadsheet. Each row represents a different test case, and the data in each column corresponds to the parameters you want to pass to your test cases. To know what type of data you should populate your sheet with, it is recommended to write out your test plan and test strategy document first. They give you a comprehensive view over your testing objectives.

Step 4: Create a data-driven test script

Once it’s already, you can write your Selenium test script to automate your test cases, but instead of hard-coding the test data, you can read it from the Excel file you prepared. To do it, you need to initiate a Workbook and Sheet object to read data.

Here’s an example of a test script written in Java using Selenium and Apache POI to test the login feature. Let’s assume that you have a ‘username’ and ‘password’ field in your XLSX file called “data.xlsx”, and the site you want to test the login feature is called “https://testwebsite.com”:


import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class DataDrivenTest { public static void main(String[] args) throws IOException { // Initialize WebDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); // Initialize Excel file FileInputStream file = new FileInputStream(new File("path/to/your/excel/data.xlsx")); Workbook workbook = new XSSFWorkbook(file); Sheet sheet = workbook.getSheet("Sheet1"); // Iterate through the rows and columns to read the data for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); String username = row.getCell(0).getStringCellValue(); String password = row.getCell(1).getStringCellValue(); // Execute the test with the current set of data driver.get("https://testwebsite.com"); WebElement usernameField = driver.findElement(By.id("username")); WebElement passwordField = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("login-button")); usernameField.sendKeys(username); passwordField.sendKeys(password); loginButton.click(); // Add verification/assertion steps here // Close the browser or perform any necessary cleanup } file.close(); driver.quit(); } }

However, please note that the previous script did not include a test reporting mechanism. To enable test logging, you need to import the java.util.logging package. Here’s the updated version for test logging mechanism:


import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class DataDrivenTest { public static void main(String[] args) throws IOException { // Initialize WebDriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); // Initialize logging Logger logger = Logger.getLogger(DataDrivenTest.class.getName()); FileHandler fileHandler = new FileHandler("test_report.log"); logger.addHandler(fileHandler); // Initialize Excel file FileInputStream file = new FileInputStream(new File("path/to/your/excel/data.xlsx")); Workbook workbook = new XSSFWorkbook(file); Sheet sheet = workbook.getSheet("Sheet1"); // Iterate through the rows and columns to read the data for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { Row row = sheet.getRow(rowNum); String username = row.getCell(0).getStringCellValue(); String password = row.getCell(1).getStringCellValue(); // Execute the test with the current set of data driver.get("https://testwebsite.com"); WebElement usernameField = driver.findElement(By.id("username")); WebElement passwordField = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("login-button")); usernameField.sendKeys(username); passwordField.sendKeys(password); loginButton.click(); // Add verification/assertion steps here // Example: You can check the URL, page title, or specific elements for expected conditions. if (driver.getCurrentUrl().equals("https://testwebsite.com/dashboard")) { logger.log(Level.INFO, "Test case PASSED: Username=" + username + ", Password=" + password); } else { logger.log(Level.SEVERE, "Test case FAILED: Username=" + username + ", Password=" + password); } // Close the browser or perform any necessary cleanup } file.close(); driver.quit(); } }

Real-Time Selenium Projects in 60 Minutes  |  Selenium Projects | Selenium Training | Edureka Live
Real-Time Selenium Projects in 60 Minutes | Selenium Projects | Selenium Training | Edureka Live

Data Driven Framework in Selenium WebDriver

Data Driven Framework is a highly effective and widely utilized automation testing framework that enables iterative development and testing. It follows the principles of data-driven testing, allowing you to drive test cases and test suites using external data feeds such as Excel Sheets (xls, xlsx), CSV files (csv), and more. By establishing a connection with the external data source, the test script seamlessly performs the required operations on the test data, ensuring efficient and accurate testing.

Using the Data Driven Framework in Selenium WebDriver, the test data set is separated from the test implementation, reducing the overall effort involved in maintaining and updating the test code. Minimal changes in the business rules will require changes in the test data set, with/without minimal (or no) changes in the test code.

Selenium WebDriver lets you perform automated cross browser testing on web applications; however, it does not have the support to perform create, read, update, and delete (CRUD) operations on external data feeds like Excel sheets, CSV files, and more. This is where third-party APIs like Apache POI has to be used since it lets you access and performs relevant operations on external data sources.

What is Selenium Framework?

The Selenium automation Framework is a code structure that makes code maintenance easy and efficient. Without frameworks, users may place the “code” and “data” at the same location which is neither reusable nor readable. Frameworks produce beneficial outcomes like increased code reusability, higher portability, reduced cost of script maintenance, better code readability, etc.

Selenium Webdriver With Java Automation Framework Development #02 | With Practical Demonstration
Selenium Webdriver With Java Automation Framework Development #02 | With Practical Demonstration

Benefits of Data-driven Testing

For software testers, DDT brings a variety of benefits:

  • Efficiency: By systematically adding new cases by updating the data source rather than writing new test scripts from the beginning, DDT significantly reduces the effort required to maintain and expand test suites.
  • Reusability: Testers are allowed to reuse the same test scripts with different sets of test data during regression testing. This means they do not have to create separate scripts for each test case, reducing redundancy and maintenance efforts.
  • Maintenance: Since test data is stored externally, any changes to test data can be made without changing the test script. This simplifies maintenance and reduces the risk of introducing errors when making updates.
  • Scalability: As the application grows and more test scenarios are required, testers can simply add more data to your external sources without modifying the test script itself, which makes the framework utterly scalable.
  • Collaboration: As the framework is already established, different team members can work on test data and test scripts concurrently, leading to better collaboration and development.
  • Faster test execution: By running the same test logic with multiple data sets in a batch, this framework can improve test execution speed, especially when combined with parallel execution.
  • Test coverage: Using various data sets, QA teams can test a wider range of scenarios, including edge cases and boundary conditions, which can improve the overall test coverage.

As a whole, DDT provides better flexibility, maintainability, and scalability for test automation efforts. Indeed, it helps QA teams streamline the testing process and improve efficiency by separating test data from test script logic.

Hybrid Driven Framework

Hybrid Driven Framework in Selenium is a concept where we are using the advantage of both Keyword driven framework as well as Data driven framework. It is an easy to use framework which allows manual testers to create test cases by just looking at the keywords, test data and object repository without coding in the framework.

Here for keywords, we will use Excel files to maintain test cases, and for test data, we can use data, provider of Testng framework.

Here in our hybrid framework, we don’t need to change anything in Keyword driven framework, here we just need to replace ExecuteTest.java file with HybridExecuteTest.java file.

This HybridExecuteTest file has all the code for keyword driven with data provider concept.

The complete pictorial representation of hybrid framework will look like

HybridExecuteTest.java

package testCases; import java.io.IOException; import java.util.Properties; import operation.ReadObject; import operation.UIOperation; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import excelExportAndFileIO.ReadGuru99ExcelFile; public class HybridExecuteTest { WebDriver webdriver = null; @Test(dataProvider=”hybridData”) public void testLogin(String testcaseName,String keyword,String objectName,String objectType,String value) throws Exception { // TODO Auto-generated method stub if(testcaseName!=null&&testcaseName.length()!=0){ webdriver=new FirefoxDriver(); } ReadObject object = new ReadObject(); Properties allObjects = object.getObjectRepository(); UIOperation operation = new UIOperation(webdriver); //Call perform function to perform operation on UI operation.perform(allObjects, keyword, objectName, objectType, value); } @DataProvider(name=”hybridData”) public Object[][] getDataFromDataprovider() throws IOException{ Object[][] object = null; ReadGuru99ExcelFile file = new ReadGuru99ExcelFile(); //Read keyword sheet Sheet guru99Sheet = file.readExcel(System.getProperty(“user.dir”)+”\\”,”TestCase.xlsx” , “KeywordFramework”); //Find number of rows in excel file int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum(); object = new Object[rowCount][5]; for (int i = 0; i < rowCount; i++) { //Loop over all the rows Row row = guru99Sheet.getRow(i+1); //Create a loop to print cell values in a row for (int j = 0; j < row.getLastCellNum(); j++) { //Print excel data in console object[i][j] = row.getCell(j).toString(); } } System.out.println(“”); return object; } }

Learn Selenium Java Hybrid Framework in 12 hours (TestNG, POM, PF, ExtentReports,Git,GitHub,Jenkins)
Learn Selenium Java Hybrid Framework in 12 hours (TestNG, POM, PF, ExtentReports,Git,GitHub,Jenkins)

Data-Driven Testing With Selenium or With an Automated Testing Tool?

There are two options when it comes to data-driven testing:

  1. You can build a data-driven testing framework from scratch leveraging other libraries and frameworks (Selenium, Apache POI, etc.).
  2. You can use an automation testing tool that comes with a data-driven testing framework that is ready to use immediately.

Let’s compare the two approaches using the example above.

In our example, you can prepare an Excel sheet with four columns: “Username”, “Password”, “Address”, and “Payment Method”. You can add as many rows as you like for different sets of user data.

Username

Password

Address

Payment Method

username1

password1

Street 1 City 1

Visa credit card

username2

password2

Street 2 City 2

Visa debit card

username3

password3

Street 3 City 3

PayPal

After that, you need to create a new Java project in your IDE and add the Selenium WebDriver and TestNG libraries to your project.

Finally, write your test script to incorporate logic to read data. In our case, the script should iterate through each username and password, use them to login to the user account, and then initiate the checkout process where it fills in the address, before initiating the payment method.

If you are not familiar with coding, check out the top automation testing tools on the market that can help you automate this process without having to write a lot of code. This is the second approach. Many automated testing tools already have a DDT framework for you to use.

If you decide to go with this approach, simply create the test cases leveraging their built-in features. Top testing tools should come with helpful test authoring features such as Built-in Keywords or Record-and-Playback, which can drastically reduce your time spent writing code. They even come with Smart Reporting features which automatically generate out-of-the-box reports with rich insights on the quality of the system under test. It’s really simple!

In other words, to do data-driven testing, follow the following steps:

  1. Prepare your test data in the form of Excel, CSV, JSON, or a database.
  2. Set up a testing framework that supports data-driven testing such as TestNG, JUnit, or libraries like Apache POI or CSVReader. You can also go with tools that have a data-driven testing framework already built-in such as Katalon Platform, Leapwork, or SmartBear so you can start testing right away without having to create everything from scratch.
  3. Create a test case with the framework/tool of your choice. Incorporate the logic to read data and execute test steps accordingly.
  4. Execute the test script and generate a report to capture test results. If your testing framework doesn’t automatically generate test reports, you also need to implement the functionality. For testing tools, this feature usually comes ready to use.
  5. Review, troubleshoot, and debug.

Let’s find out how we can do data-driven testing with Selenium and with Katalon – a comprehensive automation testing tool.

Summary

  • We can create three types of test framework using Selenium WebDriver.
  • A Selenium automation framework that can be classified into Data Driven, Keyword Driven, and Hybrid Frameworks.
  • We can achieve Data-driven framework using TestNG’s data provider.
  • In Keyword driven framework, keywords are written in some external files like excel file and java code will call this file and execute test cases.
  • The hybrid framework is a mix of keyword driven and data driven framework.

Download the Selenium Project Files for the Demo in this Tutorial

Data Driven Testing using JSON file with TestNG DataProvider
Data Driven Testing using JSON file with TestNG DataProvider

Cách tạo một Data Driven Automation Framwork

  1. Dowload Apache POI (https://poi.apache.org/download.html)
  2. Tích hợp Apache POI vào eclipse (https://www.softwaretestingmaterial.com/handling-excel-files-using-apache-poi/)
  3. Viết kịch bản test
  4. Đọc dữ liệu từ file lưu trữ
  5. Viết dữ liệu ra file lưu trữ (nếu cần)


import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class Driver { private XSSFWorkbook workbook; private XSSFSheet sheet; private XSSFCell cell; private WebDriver driver; private String url = "https://www.facebook.com/"; @BeforeTest public void TestSetup() { System.setProperty("webdriver.gecko.driver", "C:\\\\Users\\\\linhntd\\\\Downloads\\\\geckodriver-v0.20.1-win64\\\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); driver.get(url); System.out.println("Linh"); } @Test public void Read() { // Import file excel File src = new File("D:\\2018_STUDY\\test.xlsx"); FileInputStream fis; try { fis = new FileInputStream(src); workbook = new XSSFWorkbook(fis); sheet = workbook.getSheet("Sheet1"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 1; i <= sheet.getLastRowNum(); i++) { /* * I have added test data in the cell A2 as "[email protected]" and B2 as * "password" Cell A2 = row 1 and column 0. It reads first row as 0, second row * as 1 and so on and first column (A) as 0 and second column (B) as 1 and so on */ // Import data for Email. cell = sheet.getRow(i).getCell(0); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.xpath("//input[@id='email']")).clear(); driver.findElement(By.xpath("//input[@id='email']")).sendKeys(cell.getStringCellValue()); // Import data for password. cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id("pass")).clear(); driver.findElement(By.id("pass")).sendKeys(cell.getStringCellValue()); // To click on Login button driver.findElement(By.xpath("//input[@id='u_0_2']")).click(); // To write data in the excel FileOutputStream fos = null; try { fos = new FileOutputStream(src); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Message to be written in the excel sheet String message = "Pass"; // Create cell where data needs to be written. sheet.getRow(i).createCell(2).setCellValue(message); // finally write content try { workbook.write(fos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // To click on Account settings dropdown // driver.findElement(By.xpath("//div[text()='Account Settings']")).click(); // To click on logout button // driver.findElement(By.xpath("//text()[.='Log // Out']/ancestor::span[1]")).click(); // close the file try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Load he workbook. // Load the sheet in which data is stored. } }

Introduction to Data Driven Testing in Selenium WebDriver

As new functionalities (or features) are added to a web product, test cases (or test suites) must be implemented to test the new set of features. Before adding a new test case, you should have relevant answers to the following questions:

  • Do we really need to develop a new test case for verifying the corresponding functionality?
  • functionality?Is it feasible to modify an existing test case to suit the testing needs of the feature under test?
  • Is it possible to change the existing test implementation so that the said ‘product features’ can be tested against different input combinations (or data sets)?
  • Is it required to add new test implementation when there are minimal changes in the business rules?
  • Is there a more optimal way to separate the test data from the test implementation?

The answers to the questions mentioned above lie with Data Driven Testing in Selenium WebDriver.

What is Data Driven Testing?

Data Driven Testing is a strategic approach that involves executing a set of test script actions in a repetitive manner, each time utilizing distinct input values sourced from an associated data repository. This technique enhances efficiency by decoupling the ‘test_case‘ code from the underlying ‘data_set,’ streamlining testing processes.It is one of the widely-used automation testing best practices for verifying the behavior and efficiency of tests when handling various types of input values. You can learn more about the different testing methods by reading the article on TDD vs BDD: Choosing The Suitable Framework.

Here are the popular external data feed or data sources in data driven testing:

  • MS Excel Sheets (.xls, .xlsx)
  • CSV Files (.csv)
  • XML Files (.xml)
  • MS Access Tables (.mdb)

The data feed or data source not only contains the input values used for Selenium automation testing but can also be used for storing the expected test result and the output test result. This can be useful in comparing the test execution result and storing the same for referring to later stages.

Advantages of Data Driven Testing

Some of the significant benefits of Data Driven Testing are:

  • Data Driven Testing accelerates the process of efficiently performing regression testing on the features of a web product. Regression tests can be used to verify end-to-end workflow logic across using different values stored in external data sources.
  • Data Driven Tests are easier to maintain since the test logic is logically separated from the data used for testing the logic. Hence, minor business rules changes might only create new scenarios and additional data sets against which the tests have been verified.
  • Data Driven Tests are useful for record-keeping since you can store the test execution status along with the input values against which the test automation was run.
  • Data Driven Testing is a preferred choice for iteratively testing the application (or web product) against a large data set. The data set can contain input values covering positive and negative test scenarios, thereby helping achieve improved test efficiency and coverage.

Now that we have covered the basics of data driven testing let’s have a look at the Data Driven Framework in Selenium WebDriver and how data driven testing in Selenium WebDriver can be realized using Apache POI.

Page Object Model pattern with TestNG Framework | End to End Test Automation Project Selenium
Page Object Model pattern with TestNG Framework | End to End Test Automation Project Selenium

Data-driven Testing Examples

Imagine that you are the tester of an established e-commerce company. Your goal is to ensure that the checkout process is working as expected, so you want to run a test to see if users can authenticate their account seamlessly on your website. We can immediately see that this test scenario poses several challenges:

  1. How do we ensure that we cover all possible user authentication scenarios, when there are so many variations of email, passwords, social media accounts, etc. to be checked?
  2. Users tend to enter their address in a highly inconsistent manner, so how do we make sure that their address formats are valid so that no issues occur during the shipping process?
  3. What are the conditions for valid/invalid card payments?
  4. What are the promotional codes/coupons available at the moment and how do we make sure that they cause no conflicts with each other?

Those challenges can easily be addressed with data-driven testing. Instead of manually typing in specific values for each scenario (which is essentially a hard-coding approach), we can simply prepare the test data for all of the possible scenarios in one database, with each row of data representing one scenario, then write a script to read test data and execute the test steps.

Data-Driven Testing With Selenium or With an Automated Testing Tool?

There are two options when it comes to data-driven testing:

  1. You can build a data-driven testing framework from scratch leveraging other libraries and frameworks (Selenium, Apache POI, etc.).
  2. You can use an automation testing tool that comes with a data-driven testing framework that is ready to use immediately.

Let’s compare the two approaches using the example above.

In our example, you can prepare an Excel sheet with four columns: “Username”, “Password”, “Address”, and “Payment Method”. You can add as many rows as you like for different sets of user data.

Username

Password

Address

Payment Method

username1

password1

Street 1 City 1

Visa credit card

username2

password2

Street 2 City 2

Visa debit card

username3

password3

Street 3 City 3

PayPal

After that, you need to create a new Java project in your IDE and add the Selenium WebDriver and TestNG libraries to your project.

Finally, write your test script to incorporate logic to read data. In our case, the script should iterate through each username and password, use them to login to the user account, and then initiate the checkout process where it fills in the address, before initiating the payment method.

If you are not familiar with coding, check out the top automation testing tools on the market that can help you automate this process without having to write a lot of code. This is the second approach. Many automated testing tools already have a DDT framework for you to use.

If you decide to go with this approach, simply create the test cases leveraging their built-in features. Top testing tools should come with helpful test authoring features such as Built-in Keywords or Record-and-Playback, which can drastically reduce your time spent writing code. They even come with Smart Reporting features which automatically generate out-of-the-box reports with rich insights on the quality of the system under test. It’s really simple!

In other words, to do data-driven testing, follow the following steps:

  1. Prepare your test data in the form of Excel, CSV, JSON, or a database.
  2. Set up a testing framework that supports data-driven testing such as TestNG, JUnit, or libraries like Apache POI or CSVReader. You can also go with tools that have a data-driven testing framework already built-in such as Katalon Platform, Leapwork, or SmartBear so you can start testing right away without having to create everything from scratch.
  3. Create a test case with the framework/tool of your choice. Incorporate the logic to read data and execute test steps accordingly.
  4. Execute the test script and generate a report to capture test results. If your testing framework doesn’t automatically generate test reports, you also need to implement the functionality. For testing tools, this feature usually comes ready to use.
  5. Review, troubleshoot, and debug.

Let’s find out how we can do data-driven testing with Selenium and with Katalon – a comprehensive automation testing tool.

How To Explain Test Automation Framework In Interviews For Selenium
How To Explain Test Automation Framework In Interviews For Selenium

Data Driven Testing Framework in Selenium WebDriver

In this post, I will show you how to implement Data Driven Framework in Selenium WebDriver using Apache POI and TestNG data provider. There are different types of test automation frameworks in the market such as Modular, Data Driven, Keyword Driven, Page Object Model (actually it’s a design pattern), Hybrid Framework. Each type of framework has its own features.

  • 1. What is Data Driven Framework
  • 2. Why Data Driven Framework
  • 3. Advantages of using Data Driven Test Framework
  • 4. What is Apache POI
  • 5. How to work on Data Driven Framework in Selenium Using Apache POI
  • 6. How To Create Data Driven Framework in Selenium Using Apache POI
  • 7. How To Read Data From Excel Sheet Using Apache POI
  • 8. How To Write Data From Excel Sheet Using Apache POI
  • 9. Data Driven Framework in Selenium WebDriver using TestNG Data Provider

What is Data Driven Framework

Data Driven framework is focused on separating the test scripts logic and the test data from each other. Allows us to create test automation scripts by passing different sets of test data. The test data set is kept in the external files or resources such as MS Excel Sheets, MS Access Tables, SQL Database, XML files etc., The test scripts connect to the external resources to get the test data. By using this framework we could easily make the test scripts work properly for different sets of test data. This framework significantly reduces the number of test scripts compared to a modular based framework.

Why Data Driven Framework

Usually, we place all our test data in excel sheets which we use in our test runs. Assume, we need to run a test script (Say, login test) with multiple test data. If we run the same test with multiple test data sets manually is time-consuming, and error-prone. In the next section, we see a practical example.

In simple words, we adopt Data Driven Framework when we have to execute the same script with multiple sets of test data.

Advantages of using Data Driven Test Framework

  • Re-usability of code
  • Improves test coverage
  • Faster Execution
  • Less maintenance
  • Permits better error handling

What is Apache POI

Apache POI is an open source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. It is a popular API that allows working around excel files using Java Programs. In short, you can read and write MS Excel files using Java. Apache POI is your Java Excel solution.You’d use HSSF if you needed to read or write an Excel file using Java (XLS). You’d use XSSF if you need to read or write an OOXML Excel file using Java (XLSX). It has many predefined methods, classes, and interfaces.

How to work on Data Driven Framework in Selenium Using Apache POI

Selenium automates browsers. It’s a popular tool to automate web-based applications. To handle excel sheets to read and write data using Selenium we do use Apache POI.

Assume, you need to test login form with 50 different sets of test data

  1. As a manual tester, you do log in with all the 50 different sets of test data for 50 times
  2. As an automation tester, you create a test script and run 50 times by changing the test data on each run or you create 50 test scripts to execute the scenario

One of the reasons we take automation is to overcome the time consumption issue. By following the above two ways we don’t achieve anything with automation.

Data Driven testing helps here and save a lot of time of us.

How To Create Data Driven Framework in Selenium Using Apache POI

Here I will take Facebook Application to showcase implementation of Data Driven Framework in Selenium with Java using Apache POI.

Scenario: Open facebook page and do log in and log out.

Must Read: Complete Selenium WebDriver Tutorial

Follow below steps to Implement Data Driven framework.

First, we see how to read test data from excel sheet and then we see how to write the result in the excel sheet.

How To Read Data From Excel Sheet Using Apache POI

Prerequisites to implement Data Driven Framework:

  1. Eclipse IDE
  2. TestNG
  3. Selenium jars
  4. Apache POI jars
  5. Microsoft Excel

The structure of my project (Data Driven Project with Maven) is as follows:

Step 1: Open Eclipse and configure Apache POI jar files – Download Apache Jars

Note: If you are using Maven Project then you could include the dependencies in the pom.xml

Must Read: How to create Maven Project

Step 2: Open Excel Sheet and create some test data. Here I have saved my excel sheet on my D Drive.

Step 3: Create a Java Class under your Project

Here I have created a Java Class “DataDrivenTest” under my Project “DataDrivenProject”

Step 4: Here is a sample code to login to facebook.com by getting the user credentials from excel sheet. Copy the below code and paste it in your Java Class.

package tests; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class DataDrivenTest { WebDriver driver; XSSFWorkbook workbook; XSSFSheet sheet; XSSFCell cell; @BeforeTest public void initialization(){ // To set the path of the Chrome driver. System.setProperty(“webdriver.chrome.driver”, System.getProperty(“user.dir”)+”\\src\\test\\java\\drivers\\chromedriver.exe”); driver = new ChromeDriver(); // To launch facebook driver.get(“http://www.facebook.com/”); // To maximize the browser driver.manage().window().maximize(); // implicit wait driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Test public void fbLoginLogout() throws IOException{ // Import excel sheet. File src=new File(“D:\\Test.xlsx”); // Load the file. FileInputStream fis = new FileInputStream(src); // Load he workbook. workbook = new XSSFWorkbook(fis); // Load the sheet in which data is stored. sheet= workbook.getSheetAt(0); for(int i=1; i<=sheet.getLastRowNum(); i++){ /*I have added test data in the cell A2 as “[email protected]” and B2 as “password” Cell A2 = row 1 and column 0. It reads first row as 0, second row as 1 and so on and first column (A) as 0 and second column (B) as 1 and so on*/ // Import data for Email. cell = sheet.getRow(i).getCell(0); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.xpath(“//input[@type=’email’][@name=’email’]”)).clear(); driver.findElement(By.xpath(“//input[@type=’email’][@name=’email’]”)).sendKeys(cell.getStringCellValue()); // Import data for password. cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.xpath(“//input[@type=’password’][@name=’pass’]”)).clear(); driver.findElement(By.xpath(“//input[@type=’password’][@name=’pass’]”)).sendKeys(cell.getStringCellValue()); // To click on Login button driver.findElement(By.xpath(“//input[@type=’submit’][@id=’u_0_5′]”)).click(); // To click on Account settings dropdown driver.findElement(By.xpath(“//div[text()=’Account Settings’]”)).click(); // To click on logout button driver.findElement(By.xpath(“//text()[.=’Log Out’]/ancestor::span[1]”)).click(); } } }

Step 5: Run your test script

How To Write Data From Excel Sheet Using Apache POI

Step 1: Follow step 1 as mentioned above

Step 2: Here I have created another column as “Result” on my excel sheet which is on my D Drive.

Step 3: Here is a sample code to login to facebook.com by getting the user credentials from excel sheet and write the result in the excel sheet. Copy the below code and paste it in your Java Class.

package tests; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class DataDrivenTest { WebDriver driver; XSSFWorkbook workbook; XSSFSheet sheet; XSSFCell cell; @BeforeTest public void TestSetup(){ // To set the path of the Chrome driver. System.setProperty(“webdriver.chrome.driver”, System.getProperty(“user.dir”)+”\\src\\test\\java\\drivers\\chromedriver.exe”); driver = new ChromeDriver(); // To launch facebook driver.get(“http://www.facebook.com/”); // To maximize the browser driver.manage().window().maximize(); // implicit wait driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Test public void ReadData() throws IOException, Exception{ // Import excel sheet. File src=new File(“D:\\Test.xlsx”); // Load the file. FileInputStream fis = new FileInputStream(src); // Load he workbook. workbook = new XSSFWorkbook(fis); // Load the sheet in which data is stored. sheet= workbook.getSheet(“Sheet1”); for(int i=1; i<=sheet.getLastRowNum(); i++){ /*I have added test data in the cell A2 as “[email protected]” and B2 as “password” Cell A2 = row 1 and column 0. It reads first row as 0, second row as 1 and so on and first column (A) as 0 and second column (B) as 1 and so on*/ // Import data for Email. cell = sheet.getRow(i).getCell(0); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.xpath(“//input[@type=’email’][@name=’email’]”)).clear(); driver.findElement(By.xpath(“//input[@type=’email’][@name=’email’]”)).sendKeys(cell.getStringCellValue()); // Import data for password. cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.xpath(“//input[@type=’password’][@name=’pass’]”)).clear(); driver.findElement(By.xpath(“//input[@type=’password’][@name=’pass’]”)).sendKeys(cell.getStringCellValue()); // To click on Login button driver.findElement(By.xpath(“//input[@type=’submit’][@id=’u_0_5′]”)).click(); //To write data in the excel FileOutputStream fos=new FileOutputStream(src); // Message to be written in the excel sheet String message = “Pass”; // Create cell where data needs to be written. sheet.getRow(i).createCell(2).setCellValue(message); // finally write content workbook.write(fos); // To click on Account settings dropdown driver.findElement(By.xpath(“//div[text()=’Account Settings’]”)).click(); // To click on logout button driver.findElement(By.xpath(“//text()[.=’Log Out’]/ancestor::span[1]”)).click(); // close the file fos.close(); } } }

Step 4: Once it finished open the Excel file and check for the result.

Data Driven Framework in Selenium WebDriver using TestNG Data Provider

Scenario: Open Facebook and type username and password and login

Below test script runs 2 times with different sets of test data.

package tests; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataDrivenTest { // To get data from dataprovider @Test(dataProvider=”testdataset”) public void fbLoginLogout(String email, String password) throws Exception{ // Initalizing webdriver System.setProperty(“webdriver.chrome.driver”, System.getProperty(“user.dir”)+”\\src\\test\\java\\drivers\\chromedriver.exe”); WebDriver driver = new ChromeDriver(); // To maxamize the browser window driver.manage().window().maximize(); // Implicit wait of 20 seconds driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // To launch facebook driver.get(“https://www.facebook.com”); // To clear the email field driver.findElement(By.xpath(“//input[@type=’email’][@name=’email’]”)).clear(); // To pass Email driver.findElement(By.xpath(“//input[@type=’email’][@name=’email’]”)).sendKeys(email); // To clear password field driver.findElement(By.xpath(“//input[@type=’password’][@name=’pass’]”)).clear(); // To pass password driver.findElement(By.xpath(“//input[@type=’password’][@name=’pass’]”)).sendKeys(password); // To click on Login button driver.findElement(By.xpath(“//input[@type=’submit’][@id=’u_0_5′]”)).click(); // To click on Account settings dropdown driver.findElement(By.xpath(“//div[text()=’Account Settings’]”)).click(); // To click on logout button driver.findElement(By.xpath(“//text()[.=’Log Out’]/ancestor::span[1]”)).click(); } // @DataProvider passes data to test cases. Here I took 2 dimension array. @DataProvider(name=”testdataset”) public Object[][] getData(){ // Create object with two paraments // first parameter is row and second one is column Object[][] data = new Object[2][2]; data[0][0] = “[email protected]”; data[0][1] = “password”; data[1][0] = “[email protected]”; data[1][1] = “password”; return data; } }

If you have any queries please comment below in the comments section.

Page Object Model with Page Factory in Selenium – Complete Guide

Here I have hand-picked few posts which will help you to learn some interesting stuff:

  • Explain Test Automation Framework In The Interview
  • Test Automation Framework Interview Questions
  • Selenium Interview Questions
  • TestNG Interview Questions
  • Why You Choose Software Testing As A Career
  • Manual Testing Interview Questions
  • General Interview Questions
  • SQL Interview Questions
  • Agile Interview Questions
  • Selenium Tutorial
  • TestNG Tutorial
  • Manual Testing Tutorial
  • Katalon Studio Tutorial

How to create a Data Driven Automation Framework

Consider you want to Test Login functionality of an application.

Step 1) Identify the Test Cases

  • Input Correct username and password – Login Success
  • Input incorrect username and correct password – Login Failure
  • Input correct username and incorrect password – Login Failure

Step 2) Create detailed test Steps for above 3 Test Cases

Test Case# Description Test Steps Test Data Expected Results
Check Login for valid credentials Username: valid password: valid Login Success
Check Login for invalid credentials Username: invalid password: valid Login Fail
Check Login for invalid credentials Username: valid password: invalid Login Fail

Step 3) Create Test Script

If you observe the Test Steps Remain common through the 3 Test Steps. You need to create a Test Script to execute these steps

// This is Pseudo Code // Test Step 1: Launch Application driver.get(“URL of the Application”); // Test Step 2: Enter Username txtbox_username.sendKeys(“valid”); // Test Step 3: Enter Password txtbox_password.sendKeys(“invalid”); // Test Step 4: Check Results If (Next Screen) print success else Fail

Step 4) Create an excel/csv with the Input Test Data

Step 5) Step Modify the Scrip to Loop over Input Test Data. The input commands should also be parameterized

// This is Pseudo Code // Loop 3 Times for (i = 0; i & lt; = 3; i++) { // Read data from Excel and store into variables int input_1 = ReadExcel(i, 0); int input_2 = ReadExcel(i, 1); // Test Step 1: Launch Application driver.get(“URL of the Application”); // Test Step 2: Enter Username txtbox_username.sendKeys(input_1); // Test Step 3: Enter Password txtbox_password.sendKeys(input_2); // Test Step 4: Check Results If(Next Screen) print success else Fail }

Above are just 3 test cases. The test script can be used to loop over following test cases just by appending test data values to Excel

  • Input incorrect username and incorrect password – Login Fail
  • Input correct username and password blank – Login Fail
  • Input blank username and blank password– Login Fail

And so on

Why Do We Need Frameworks For Test Automation | Automation Testing Framework Using Selenium
Why Do We Need Frameworks For Test Automation | Automation Testing Framework Using Selenium

Perform Cross Browser Testing in Selenium using Apache POI

In all the examples we showcased so far, the test data was fetched from an external data feed (i.e., xls/xlsx), and the test data was used in running the same test against different data sets. What if you intend to run a cross browser test where the online browser & OS combinations are read from an external file (xls/xlsx).

In this section, we look at how the APIs provided by the Apache POI library can be leveraged for running a cross browser test. First, here is the snapshot of the Excel file (Test_3.xls), which contains the required setting of the Desired Capabilities for the Remote WebDriver.

As shown above, the same test is run against two different virtual browser combinations:

  • Chrome 87.0 (on Windows 10)
  • Chrome 83.0 (on macOS Catalina)

Test Scenario

  1. Go to https://lambdatest.com/automation-demos
  2. Run the steps (3) thru (7) for the browser & OS combinations specified in the external Excel file.
  3. Click on the ‘I Accept’ button
  4. Scroll to the End of the Page
  5. Find the element with link ‘List of Browsers’ and click on the element
  6. Check if the current page URL is https://www.lambdatest.com/list-of-browsers and set the Test Result accordingly
  7. Write the test result at appropriate Cells in the excel sheet

Implementation

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

package com.DataDrivenFramework;

import java.io.*;

import java.net.URL;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.Assert;

import org.testng.annotations.Test;

public class test_LT_DataDrivenFramework

WebDriver driver;

XSSFWorkbook workbook;

Sheet sheet;

Cell cell;

public static String username = “user-name”;

public static String access_key = “access-key”;

@Test(description = “[CBT]: Testing data input from XLS (i.e. HSSF)”, priority = 1, enabled = true)

public void Test_ddf_cbt_input() throws IOException, InterruptedException {

String[] test_combs = new String[5];

Integer cnt = 0;

String test_url = “https://lambdatest.com/automation-demos/”;

HSSFWorkbook workbook;

/* Import the Excel Sheet */

File src = new File(“C:\\Folder\\Test_3.xls”);

/* Load the File */

FileInputStream fis = new FileInputStream(src);

/* Load the Workbook */

workbook = new HSSFWorkbook(fis);

/* The Excel file contains two sheets:

Sheet 1 – Browser and OS Combination

*/

/* Load the data in Sheet 0 for creating an instance of Remote WebDriver */

sheet = workbook.getSheetAt(0);

/* Get the relevant capabilities headings from row – 0 */

while (cnt < 5)

cell = sheet.getRow(0).getCell(cnt);

test_combs[cnt] = cell.getStringCellValue();

cnt++;

/* Assign the capabilities from row – 1 onwards */

for(int row_cnt = 1; row_cnt <= sheet.getLastRowNum(); row_cnt++)

DesiredCapabilities capabilities = new DesiredCapabilities();

for (cnt = 0; cnt < 5; cnt++)

String props = sheet.getRow(row_cnt).getCell(cnt).getStringCellValue();

capabilities.setCapability(test_combs[cnt], props);

capabilities.setCapability(“tunnel”, false);

capabilities.setCapability(“network”, true);

capabilities.setCapability(“console”, true);

capabilities.setCapability(“visual”, true);

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”),

capabilities);

/* Now comes the test scenario */

driver.get(test_url);

WebElement elem_accept = driver.findElement(By.xpath(“//a[.=’I ACCEPT’]”));

elem_accept.click();

Thread.sleep(3000);

/* Scroll till the end of the page */

((JavascriptExecutor)driver).executeScript(“window.scrollBy(0,document.body.scrollHeight)”);

WebElement elem_brow_list = driver.findElement(By.xpath(“//a[.=’List of Browsers’]”));

elem_brow_list.click();

Thread.sleep(3000);

Assert.assertEquals(driver.getCurrentUrl(), “https://www.lambdatest.com/list-of-browsers”);

/* Update result in the excel sheet */

/* Write Data in the Result Column */

FileOutputStream fos = new FileOutputStream(src);

String message = “Passed”;

sheet.getRow(row_cnt).createCell(6).setCellValue(message);

workbook.write(fos);

fos.close();

System.out.println(“CBT test to demo Data Driven Framework successful\n”);

driver.quit();

Code Walkthrough

1. Create an instance of Selenium WebDriver, HSSFWorkBook, Sheet, and Cell, respectively.

WebDriver driver;

HSSFWorkbook workbook;

Sheet sheet;

Cell cell;

2. Import the Excel Sheet and load the file using FileInputStream

File src = new File(“C:\\Folder\\Test_3.xls”);

workbook = new HSSFWorkbook(fis);

3. Create an object of HSSFWorkbook and load the data in the Sheet ‘0’ where the fields for creating the Desired Capabilities are present.

sheet = workbook.getSheetAt(0);

4. The first row (i.e., row – 0) contains strings indicating the respective fields used to create the Capabilities (i.e., build, name, platformName, browserName, etc.). It is inline with what has to be passed in terms of DesiredCapabilities to the Remote WebDriver.

In a while loop (with end count as 4), the String Value in Cell (0,0)..Cell (0,4) is read and populated in a String array ( test_combs[] ). This array only contains the Capabilities that have to be set (i.e., build, name, etc.).

while (cnt < 5)

cell = sheet.getRow(0).getCell(cnt);

test_combs[cnt] = cell.getStringCellValue();

cnt++;

5. From row – 1 onwards, we start assigning values to set the DesiredCapabilities. Then, in a for loop (0..4), we read the String value from each cell and assign the same to the corresponding String element from the array test_combs[].

For Combination – 1

  • test_combs[0] 🡪 build (capability) is set to ‘Data Driven Framework..’ [String value from Cell (1,0)].
  • test_combs[1] 🡪 name (capability) is set to ‘Data Driven Framework..’ [String value from Cell (1,1)].
  • test_combs[2] 🡪 platformName (capability) is set to Windows 10 [String value from Cell (1,2)].
  • test_combs[3] 🡪 browserName (capability) is set to Chrome [String value from Cell (1,3)].
  • test_combs[4] 🡪 browserVersion (capability) is set to 87.0 [String value from Cell (1,4)].

The same set of actions are repeated for Test Combination – 2, the capabilities of which are present in Cell (2,0) thru Cell (2,4).

DesiredCapabilities capabilities = new DesiredCapabilities();

for (cnt = 0; cnt < 5; cnt++)

String props = sheet.getRow(row_cnt).getCell(cnt).getStringCellValue();

capabilities.setCapability(test_combs[cnt], props);

6. Now that the DesiredCapabilities are set, an instance of Remote WebDriver is created with Selenium Grid set to cloud-based Selenium Grid on LambdaTest [@hub.lambdatest.com/wd/hub].

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”), capabilities);

7. We navigate to the desired test URL (i.e. https://lambdatest.com/automation-demos)

String test_url = “https://lambdatest.com/automation-demos/”;

driver.get(test_url);

8. One the test URL, locate the ‘I Accept’ button using the XPath property and click on the located WebElement.

WebElement elem_accept = driver.findElement(By.xpath(“//a[.=’I ACCEPT’]”));

elem_accept.click();

9. Scroll to the end of the web page by invoking the “window.scrollBy” method in JavaScript. The executeScript command executes the scrollBy method in the context of the currently selected window.

((JavascriptExecutor)driver).executeScript(“window.scrollBy(0,document.body.scrollHeight)”);

10. Locate the WebElement ‘List of Browsers’ using the XPath property and click on the element.

WebElement elem_brow_list = driver.findElement(By.xpath(“//a[.=’List of Browsers’]”));

elem_brow_list.click();

11. Assert is thrown if the current URL does not match the expected URL.

Assert.assertEquals(driver.getCurrentUrl(), “https://www.lambdatest.com/list-of-browsers”);

12. We use the Java FileOutputStream class, an output stream used for writing data in the file. The Excel Workbook, which has the test data (i.e., Path_To_File\File.xls), is opened to write the test result.

  • Test Combination – 1: Test result to be written to Cell (1,6)
  • Test Combination – 2: Test result to be written to Cell (2,6)

The setCellValue method offered by the HSSFCell class is used for writing the test result (i.e., Passed) to the cells shown above.

FileOutputStream fos = new FileOutputStream(src);

String message = “Passed”;

sheet.getRow(row_cnt).createCell(6).setCellValue(message);

13. We write to the OutputStream (i.e. fos), post which we close the Output Stream using the close() method.

workbook.write(fos);

fos.close();

Execution

The test was successfully run against the browser & OS combinations mentioned in the Excel Sheet. Therefore, the test status is also updated in the cells with the title ‘Result.’

We also executed all the approaches demonstrated earlier in a single go, and the test execution was successful:

The Automation Dashboard in LambdaTest indicates the status of the test execution.

As seen above, the tests were successfully executed on LambdaTest’s cloud-based Selenium Grid.

Benefits of Data-driven Testing

For software testers, DDT brings a variety of benefits:

  • Efficiency: By systematically adding new cases by updating the data source rather than writing new test scripts from the beginning, DDT significantly reduces the effort required to maintain and expand test suites.
  • Reusability: Testers are allowed to reuse the same test scripts with different sets of test data during regression testing. This means they do not have to create separate scripts for each test case, reducing redundancy and maintenance efforts.
  • Maintenance: Since test data is stored externally, any changes to test data can be made without changing the test script. This simplifies maintenance and reduces the risk of introducing errors when making updates.
  • Scalability: As the application grows and more test scenarios are required, testers can simply add more data to your external sources without modifying the test script itself, which makes the framework utterly scalable.
  • Collaboration: As the framework is already established, different team members can work on test data and test scripts concurrently, leading to better collaboration and development.
  • Faster test execution: By running the same test logic with multiple data sets in a batch, this framework can improve test execution speed, especially when combined with parallel execution.
  • Test coverage: Using various data sets, QA teams can test a wider range of scenarios, including edge cases and boundary conditions, which can improve the overall test coverage.

As a whole, DDT provides better flexibility, maintainability, and scalability for test automation efforts. Indeed, it helps QA teams streamline the testing process and improve efficiency by separating test data from test script logic.

Manual & Automation Testing Interview | 3 to 4 Years Automation Testing Interview Questions
Manual & Automation Testing Interview | 3 to 4 Years Automation Testing Interview Questions

What is Data-driven Testing?

Data-driven testing (DDT) is a testing method where you use different types of test data to run the same test script or test case. Instead of creating separate test scripts for each input data, DDT allows you to reuse your test code. Its primary goal is to validate application behavior under a wide range of input conditions, focusing on executing the same test logic using multiple data sets to ensure the application behaves accurately in different scenarios.

At its core, DDT is a process with the following four steps:

  • Capturing embedded data from external data sources such as spreadsheets, CSV files, or databases.
  • Using available automated test scripts and variables, enter the input data in the AUT (application under test).
  • Making a comparison between actual output with expected results.
  • Executing the same test logic again for each data set.

Imagine testing a login functionality where you want to check various scenarios: valid login, invalid login, login with different user roles, and so on. Instead of writing separate scripts for each scenario, DDT lets you input different usernames and passwords from your data source, automatically running the tests for all combinations.

Output

Upon Executing the script, the output is displayed in the console as shown below.

Data Driven Testing Framework

Bài đăng này đã không được cập nhật trong 5 năm

Chào các bạn hôm nay mình sẽ giới thiệu đến các bạn một Framwork quen thuộc khi làm việc với SeleniumWebdriver : Data Driven Framwork. Do mình vừa tìm hiểu vừa viết bài này nên có gì sai sót mong các bạn hãy comment để góp ý thêm cho mình
Nội dung của bài gồm

  1. Data Driven Testing là gì
  2. Tại sao lại sử dụng Data Driven Testing
  3. Như nào để tạo một Data Driven Automation Framework
  4. Ưu điểm của Data- Driven testing
  5. Nhược điểm của Data – Driven testing
  6. Một vài ví dụ về Data Driven testing
End to End Selenium Framework | E-Commerce Project | Complete Selenium Framework from Scratch|
End to End Selenium Framework | E-Commerce Project | Complete Selenium Framework from Scratch|

Conclusion

Data Driven Testing is one of the ideal ways for performing testing at scale. Separation of test data from Functional tests is one of the major advantages of the Data Driven Framework in Selenium. The separation of test data from the tests ensures that minimal changes in the business rules do not result in changes in the test implementation. This also avoids rewriting of test code when testing against multiple sets of data.

Apache POI is a popular library that provides APIs for performing CRUD (Create, Read, Update, and Delete) operations on external data sources like MS Excel Sheets, MS Access databases, and more. Data Driven Framework in Selenium is used along with Apache POI for performing data-driven testing using different test combinations. External data sources like Excel Sheets can also supply different browser & OS combinations for realizing cross browser testing for web projects.

Keyword Driven Framework in Selenium

Keyword Driven Framework in Selenium is a method used for speeding up automated testing by separating keywords for common set of functions and instructions. All the operations and instructions to be performed are written in some external file like an Excel sheet. Users can easily control and specify the functionalities they want to test.

Here is how the complete framework looks like

As you can see it’s a 5 step framework. Let’s study it stepwise in detail

Step 1)

  • The driver script Execute.java will call ReadGuru99ExcelFile.java
  • ReadGuru99ExcelFile.java has POI script to read data from an Excel

Step 2)

  • ReadGuru99ExcelFile.java will read data from TestCase.xlsx
  • Here is how the sheet looks like-
  • According to the keywords written in Excel file, the framework will perform the operation on UI.
  • For example, we need to click a button ‘Login.’ Correspondingly, our Excel will have a keyword ‘Click.’ Now the AUT can have hundreds of button on a page, to identify a Login button, in Excel we will input Object Name as loginButton & object type as a name (see highlighted the row in above image). The Object Type could be Xpath, name CSS or any other value

Step 3) ReadGuru99ExcelFile.java will pass this data to the driver script Execute.java

Step 4)

  • For all of our UI web elements, we need to create an object repository where we will place their element locator (like Xpath, name, CSS path, class name etc.)
  • Execute.java (our driver script) will read the entire Object Repository and store it in a variable
  • To read this object repository, we need a ReadObject class which has a getObjectRepository method to read it.

NOTE: You may think why do we need to create an object repository. The answer helps in code maintenance. For example, we are using the button with name = btnlogin in 10 different test cases. In future, the developer decides to change the name from btnlogin to submit. You will have to make a change in all the 10 test cases. In the case of an object repository, you will make the change just once in the repository.

Step 5)

  • The driver will pass the data from Excel & Object Repository to UIOperation class
  • UIOperation class has functions to perform actions corresponding to keywords like CLICK, SETTEXT etc… mentioned in the excel
  • UIOperation class is a Java class which has the actual implementation of the code to perform operations on web elements

The complete project will look like-

Let’s look into an example:

Test Scenario: We are executing 2 test cases

  • Test Case 1:
  • Goto

    http://demo.guru99.com/V4/
  • Enter User ID
  • Enter Password
  • Click Reset
  • Test Case 2:
  • Goto

    http://demo.guru99.com/V4/
  • Enter User ID
  • Enter Password
  • Click Login

object.properties

url=

http://demo.guru99.com/V4/

username=uid password=password title=barone loginButton=btnLogin resetButton=btnReset

ReadGuru99ExcelFile.java

package excelExportAndFileIO; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadGuru99ExcelFile { public Sheet readExcel(String filePath,String fileName,String sheetName) throws IOException{ //Create a object of File class to open xlsx file File file = new File(filePath+”\\”+fileName); //Create an object of FileInputStream class to read excel file FileInputStream inputStream = new FileInputStream(file); Workbook guru99Workbook = null; //Find the file extension by spliting file name in substing and getting only extension name String fileExtensionName = fileName.substring(fileName.indexOf(“.”)); //Check condition if the file is xlsx file if(fileExtensionName.equals(“.xlsx”)){ //If it is xlsx file then create object of XSSFWorkbook class guru99Workbook = new XSSFWorkbook(inputStream); } //Check condition if the file is xls file else if(fileExtensionName.equals(“.xls”)){ //If it is xls file then create object of XSSFWorkbook class guru99Workbook = new HSSFWorkbook(inputStream); } //Read sheet inside the workbook by its name Sheet guru99Sheet = guru99Workbook.getSheet(sheetName); return guru99Sheet; } }

ReadObject.java

package operation; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ReadObject { Properties p = new Properties(); public Properties getObjectRepository() throws IOException{ //Read object repository file InputStream stream = new FileInputStream(new File(System.getProperty(“user.dir”)+”\\src\\objects\\object.properties”)); //load all objects p.load(stream); return p; } }

UIOperation.java

package operation; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class UIOperation { WebDriver driver; public UIOperation(WebDriver driver){ this.driver = driver; } public void perform(Properties p,String operation,String objectName,String objectType,String value) throws Exception{ System.out.println(“”); switch (operation.toUpperCase()) { case “CLICK”: //Perform click driver.findElement(this.getObject(p,objectName,objectType)).click(); break; case “SETTEXT”: //Set text on control driver.findElement(this.getObject(p,objectName,objectType)).sendKeys(value); break; case “GOTOURL”: //Get url of application driver.get(p.getProperty(value)); break; case “GETTEXT”: //Get text of an element driver.findElement(this.getObject(p,objectName,objectType)).getText(); break; default: break; } } /** * Find element BY using object type and value * @param p * @param objectName * @param objectType * @return * @throws Exception */ private By getObject(Properties p,String objectName,String objectType) throws Exception{ //Find by xpath if(objectType.equalsIgnoreCase(“XPATH”)){ return By.xpath(p.getProperty(objectName)); } //find by class else if(objectType.equalsIgnoreCase(“CLASSNAME”)){ return By.className(p.getProperty(objectName)); } //find by name else if(objectType.equalsIgnoreCase(“NAME”)){ return By.name(p.getProperty(objectName)); } //Find by css else if(objectType.equalsIgnoreCase(“CSS”)){ return By.cssSelector(p.getProperty(objectName)); } //find by link else if(objectType.equalsIgnoreCase(“LINK”)){ return By.linkText(p.getProperty(objectName)); } //find by partial link else if(objectType.equalsIgnoreCase(“PARTIALLINK”)){ return By.partialLinkText(p.getProperty(objectName)); }else { throw new Exception(“Wrong object type”); } } }

ExecuteTest.java

package testCases; import java.util.Properties; import operation.ReadObject; import operation.UIOperation; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import excelExportAndFileIO.ReadGuru99ExcelFile; public class ExecuteTest { @Test public void testLogin() throws Exception { // TODO Auto-generated method stub WebDriver webdriver = new FirefoxDriver(); ReadGuru99ExcelFile file = new ReadGuru99ExcelFile(); ReadObject object = new ReadObject(); Properties allObjects = object.getObjectRepository(); UIOperation operation = new UIOperation(webdriver); //Read keyword sheet Sheet guru99Sheet = file.readExcel(System.getProperty(“user.dir”)+”\\”,”TestCase.xlsx” , “KeywordFramework”); //Find number of rows in excel file int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum(); //Create a loop over all the rows of excel file to read it for (int i = 1; i < rowCount+1; i++) { //Loop over all the rows Row row = guru99Sheet.getRow(i); //Check if the first cell contain a value, if yes, That means it is the new testcase name if(row.getCell(0).toString().length()==0){ //Print testcase detail on console System.out.println(row.getCell(1).toString()+”—-“+ row.getCell(2).toString()+”—-“+ row.getCell(3).toString()+”—-“+ row.getCell(4).toString()); //Call perform function to perform operation on UI operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(), row.getCell(3).toString(), row.getCell(4).toString()); } else{ //Print the new testcase name when it started System.out.println(“New Testcase->”+row.getCell(0).toString() +” Started”); } } } }

After execution, output will look like –

Download the Selenium Project Files for the Demo in this Tutorial

P16 - What is a Dataprovider and how to use it in TestNG | TestNG | Testing Framework |
P16 – What is a Dataprovider and how to use it in TestNG | TestNG | Testing Framework |

Software Testing and Automation Internship Pr …

  • 1k Enrolled Learners
  • Weekend/Weekday
  • Live Class

The previous Selenium blogs in this series have given you exposure to basic concepts in Selenium testing. However, in this blog, I will tell you how to use a Selenium framework to optimize your code structure and this will move you closer to getting certified with the Selenium Certification.

Selenium framework is a code structure for making code maintenance simpler, and code readability better. A framework involves breaking the entire code into smaller pieces of code, which test a particular functionality.

The code is structured such that, the “data set” is separated from the actual “test case” which will test the functionality of the web application. It can also be structured in a way wherein, the test cases which need to be executed are called (invoked) from an external application (like a .csv).

There are a number of frameworks out there, but 3 commonly used Selenium framework (s) are:

These frameworks will be discussed with a demo in this blog. But before going any further, let me tell you why a Selenium framework needs to be in place, and what benefits you will get out of using them.

Without a framework in place, there will be one test case which will comprise the entire test functionality. The scary part is, this single test case has the capability to rise up to a million lines of code. So its pretty obvious that a test case so huge will be tough to read. Even if you want to modify any functionality later, then you will have a tough time modifying the code.

Since the implementation of a framework, will result in smaller but multiple code pieces, there are various benefits.

Find out our Selenium Testing Course in Top Cities

India United States Other Countries
Selenium Training in India Selenium Training in Chicago Selenium Certification UK
Selenium Training in Kolkata Selenium Training in New York Selenium Training in Singapore
Software Testing course in Delhi Selenium Training in USA Selenium Training Sydney

Now that you know the basics of frameworks, let me explain each of them in detail.

A Data Driven framework in Selenium is the technique of separating the “data set” from the actual “test case” (code). This framework completely depends on the input test data. The test data is fed from external sources such as an excel file, .CSV file or any database.

Since the test case is separated from the data set, we can easily modify the test case of a particular functionality without making wholesale changes to your code. For example, if you want to modify the code for login functionality, then you can modify just that instead of having to also modify any other dependent portion in the same code.

Besides this, you can also easily control how much data needs to be tested. You can easily increase the number of test parameters by adding more username and password fields to the excel file (or other sources).

For example, if I have to check the login to a web page, then I can keep the set of username and password credentials in an excel file and pass the credentials to the code to perform automation on the browser in a separate Java class file.

WebDriver does not directly support reading of excel files. Hence we use Apache POI for reading/ writing to any Microsoft office document. You can download Apache POI (set of JAR files) from here. Download the zip file or tar file as per your requirement and place them along with the set of Selenium JARs.

The co-ordination between the main code and data set will be taken care by TestNG Data Providers, which is a library that comes as a part of the Apache POI JAR files. For demo purpose, I have created an excel file called “LoginCredentials” in which the usernames and passwords have been stored in different columns.

Take a look at the below code to understand the test case. It is a simple code for testing the login functionality of a flight booking application.

package DataDriven; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DDTExcel { ChromeDriver driver; @Test(dataProvider=”testdata”) public void DemoProject(String username, String password) throws InterruptedException { System.setProperty(“webdriver.chrome.driver”, “C:UsersVardhanDownloadschromedriver.exe”); driver = new ChromeDriver(); driver.get(“http://newtours.demoaut.com/”); driver.findElement(By.name(“userName”)).sendKeys(username); driver.findElement(By.name(“password”)).sendKeys(password); driver.findElement(By.name(“login”)).click(); Thread.sleep(5000); Assert.assertTrue(driver.getTitle().matches(“Find a Flight: Mercury Tours:”), “Invalid credentials”); System.out.println(“Login successful”); } @AfterMethod void ProgramTermination() { driver.quit(); } @DataProvider(name=”testdata”) public Object[][] TestDataFeed() { ReadExcelFile config = new ReadExcelFile(“C:UsersVardhanworkspaceSeleniumLoginCredentials.xlsx”); int rows = config.getRowCount(0); Object[][] credentials = new Object[rows][2]; for(int i=0;i

If you noticed from above, we have a method named “TestDataFeed()”. In this method, I have created an object instance of another class named “ReadExcelFile”. While instantiating this object, I have fed the path of my excel file containing the data. I have further defined a for loop to retrieve the text from the excel workbook.

But, for reading the data from a given sheet number, column number and row number, the calls are made to the “ReadExcelFile” class. The code of my “ReadExcelFile” is below.

package DataDriven; import java.io.File; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFile { XSSFWorkbook wb; XSSFSheet sheet; public ReadExcelFile(String excelPath) { try { File src = new File(excelPath); FileInputStream fis = new FileInputStream(src); wb = new XSSFWorkbook(fis); } catch(Exception e) { System.out.println(e.getMessage()); } } public String getData(int sheetnumber, int row, int column) { sheet = wb.getSheetAt(sheetnumber); String data = sheet.getRow(row).getCell(column).getStringCellValue(); return data; } public int getRowCount(int sheetIndex) { int row = wb.getSheetAt(sheetIndex).getLastRowNum(); row = row + 1; return row; } }

First note the libraries I have imported. I have imported Apache POI XSSF libraries which are used to read/ write data to excel files. Here, I have created a constructor (object of the same method) to pass the values: sheet number, row number and column number. To understand this framework better, I request you to go through the below video, where I have explained this in a structured manner.

Now let’s move on to the framework, i.e Keyword Driven framework.

Keyword Driven framework is a technique in which all the operations & instructions to be performed are written separately from the actual test case. The similarity it has with Data Driven framework is that, the operations to be performed is again stored in an external file like Excel sheet.

The operations I’m talking about is nothing but the methods that need to be executed as part of a test case. The benefit with Keyword Driven framework is that you can easily control the functionalities you want to test. You can specify the methods which test the functionality of the application in the excel file. Thus, only those method names which are specified in the excel will be tested.

For example, for logging into the web application, we can write multiple methods in the main test case, in which each test case will test certain functionality. For instantiating the browser driver there could be one method, for finding the username & password fields, there could be methods, for navigating to a web page there could be another method, etc.

Take a look at the below code for understanding how the framework looks. The lines which are commented out in the below code serve as explanation if you don’t understand.

package KeywordDriven; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class Actions { public static WebDriver driver; public static void openBrowser() { System.setProperty(“webdriver.chrome.driver”, “C:UsersVardhanDownloadschromedriver.exe”); driver=new ChromeDriver(); } public static void navigate() { driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(“http://newtours.demoaut.com”); } public static void input_Username() { driver.findElement(By.name(“userName”)).sendKeys(“mercury”); } public static void input_Password() { driver.findElement(By.name(“password”)).sendKeys(“mercury”); } public static void click_Login() { driver.findElement(By.name(“login”)).click(); } @Test public static void verify_login() { String pageTitle = driver.getTitle(); Assert.assertEquals(pageTitle, “Find a Flight: Mercury Tours:”); } public static void closeBrowser() { driver.quit(); } }

As you can see, the different functionalities which need to be tested are present in separate methods waiting to be called. Now, these methods will be called from another Class, based on the presence of the method name in the excel file. And similarly, to read the excel file, and send back the results, I have written another Class. Both of them are displayed below.

The class file invoking the methods, is this.

package KeywordDriven; public class DriverScript { public static void main(String[] args) throws Exception { //Declaring the path of the Excel file with the name of the Excel file String sPath = “C:UsersVardhanworkspaceSelenium Frameworks DemodataEngine.xlsx”; //Here we are passing the Excel path and SheetName as arguments to connect with Excel file ReadExcelData.setExcelFile(sPath, “Sheet1”); //Hard coded values are used for Excel row & columns for now //Hard coded values are used for Excel row & columns for now //In later chapters we will replace these hard coded values with varibales //This is the loop for reading the values of the column 3 (Action Keyword) row by row for (int iRow=1;iRow<=7;iRow++) { String sActions = ReadExcelData.getCellData(iRow, 1); //Comparing the value of Excel cell with all the keywords in the “Actions” class if(sActions.equals(“openBrowser”)) { //This will execute if the excel cell value is ‘openBrowser’ //Action Keyword is called here to perform action Actions.openBrowser(); } else if(sActions.equals(“navigate”)) { Actions.navigate(); } else if(sActions.equals(“input_Username”)) { Actions.input_Username(); } else if(sActions.equals(“input_Password”)) { Actions.input_Password(); } else if(sActions.equals(“click_Login”)) { Actions.click_Login(); } else if(sActions.equals(“verify_Login”)) { Actions.verify_login(); } else if(sActions.equals(“closeBrowser”)) { Actions.closeBrowser(); } } } }

And the class file which reads the Excel values is this.

package KeywordDriven; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; public class ReadExcelData { private static XSSFSheet ExcelWSheet; private static XSSFWorkbook ExcelWBook; private static XSSFCell Cell; //This method is to set the File path and to open the Excel file //Pass Excel Path and SheetName as Arguments to this method public static void setExcelFile(String Path,String SheetName) throws Exception { FileInputStream ExcelFile = new FileInputStream(Path); ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); } //This method is to read the test data from the Excel cell //In this we are passing parameters/arguments as Row Num and Col Num public static String getCellData(int RowNum, int ColNum) throws Exception { Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum); String CellData = Cell.getStringCellValue(); return CellData; } }

Now, let’s move onto the final part of this Selenium framework blog, where I will show you how to build a Hybrid framework.

For details, You can even check out test automation strategies and methodology concepts with the Automation testing online course.

Hybrid framework is a technique wherein we can make the best use of both Data Driven & Keyword Driven Selenium framework (s). Using the examples shown above in this blog, we can build a Hybrid framework by storing the methods to execute in an excel file (keyword driven approach) and passing these method names to the Java Reflection Class (data driven approach) instead of creating an If/Else loop in the “DriverScript” class.

Take a look at the modified “DriverScript” class in the below code snippet. Here, instead of using multiple If/ Else loops, data driven approach is used to read the method names from the excel file.

package HybridFramework; import java.lang.reflect.Method; public class DriverScriptJava { //This is a class object, declared as ‘public static’ //So that it can be used outside the scope of main[] method public static Actions actionKeywords; public static String sActions; //This is reflection class object, declared as ‘public static’ //So that it can be used outside the scope of main[] method public static Method method[]; public static void main(String[] args) throws Exception { //Declaring the path of the Excel file with the name of the Excel file String sPath = “C:UsersVardhanworkspaceSelenium Frameworks DemodataEngine.xlsx”; //Here we are passing the Excel path and SheetName to connect with the Excel file //This method was created previously ReadExcelData.setExcelFile(sPath, “Sheet1”); //Hard coded values are used for Excel row & columns for now //Later on, we will use these hard coded value much more efficiently //This is the loop for reading the values of the column (Action Keyword) row by row //It means this loop will execute all the steps mentioned for the test case in Test Steps sheet for (int iRow=1;iRow<=7;iRow++) { sActions = ReadExcelData.getCellData(iRow, 1); //A new separate method is created with the name ‘execute_Actions’ //You will find this method below of the this test //So this statement is doing nothing but calling that piece of code to execute execute_Actions(); } } //This method contains the code to perform some action //As it is completely different set of logic, which revolves around the action only, it makes sense to keep it separate from the main driver script //This is to execute test step (Action) private static void execute_Actions() throws Exception { //Here we are instantiating a new object of class ‘Actions’ actionKeywords = new Actions(); //This will load all the methods of the class ‘Actions’ in it. //It will be like array of method, use the break point here and do the watch method = actionKeywords.getClass().getMethods(); //This is a loop which will run for the number of actions in the Action Keyword class //method variable contain all the method and method.length returns the total number of methods for(int i = 0;i

Learn more about testing methodologies and their concepts from the Manual testing course online.

To understand this concept of Data Driven, Keyword Driven & Hybrid Driven frameworks better, I request you to watch the below video.

I hope this blog was useful to you and gave you a clear understanding of what a Selenium framework is, how it is beneficial and how to build your code structure using these 3 Selenium frameworks. Stay tuned to more blogs in this series.

If you wish to learn Selenium and build a career in the testing domain, then check out our interactive, live-online Selenium Certification Training here, which comes with 24*7 support to guide you throughout your learning period. The concepts related to “Selenium Framework” has an in-depth coverage in Edureka’s course.

Got a question for us? Please mention it in the comments section and we will get back to you or join our Selenium Training in Denver today.

Course Name Date Details
Selenium Certification Training Course

Class Starts on 24th February,2024

24th February

SAT&SUN (Weekend Batch)

View Details
Selenium Certification Training Course

Class Starts on 18th March,2024

18th March

MON-FRI (Weekday Batch)

View Details
Selenium Certification Training Course

Class Starts on 30th March,2024

30th March

SAT&SUN (Weekend Batch)

View Details

edureka.co

Selenium Framework: Data, Keyword & Hybrid Driven

How to create Data Driven Framework in Selenium WebDriver using Apache POI

In this section of this Selenium Java tutorial, we look at how to perform read, write, and update operations on Excel files that are available in the .xls and .xlsx formats. Here are the prerequisites for implementing the Data Driven Framework in Selenium:

  • IDE – IntelliJ IDEA (or Eclipse IDE)
  • Framework – TestNG
  • MS Excel – .xls and .xlsx files that would contain the data for realizing data driven testing

For demonstration, we create a Data Driven Project with Maven with the following structure:

The following class files are created under the package named ‘DataDrivenFramework’:

  • test_DataDrivenFramework.java
  • test_LT_DataDrivenFramework.java

The tests demonstrating Data Driven Framework in Selenium WebDriver are run on cloud-based online Selenium Grid by LambdaTest. To get started with LambdaTest, we create a profile on LambdaTest and note the user name & access key available on the LambdaTest profile page. Then, the Desired Capabilities for the browser & OS combination under test is generated using the LambdaTest Capabilities Generator, and the respective tests are run on LambdaTest’s Selenium 4 Grid.

Shown below is pom.xml (that contains the required dependencies) and testng.xml (that contains the test classes to be run):

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>


4.0.0


org.ddf


DataDrivenFramework


1.0-SNAPSHOT


org.testng


testng


6.9.10


test


org.slf4j


slf4j-nop


1.7.28


test


org.seleniumhq.selenium


selenium-java


4.0.0-alpha-7


org.seleniumhq.selenium


selenium-remote-driver


4.0.0-alpha-7


org.seleniumhq.selenium


selenium-chrome-driver


4.0.0-alpha-7


junit


junit


4.12


test


org.apache.poi


poi


4.1.2


org.apache.poi


poi-ooxml


4.1.2


test


install


maven-compiler-plugin


3.0

1.8


1.8


org.apache.maven.plugins


maven-compiler-plugin

11


11

10

11

12

Now, let’s look at the different ways in which Data Driven Framework in Selenium is used along with Apache POI for running automated browser testing scenarios.

Read and Write data from & to Excel sheets (.xls) in Selenium using Apache POI

For performing CRUD operations on MS Excel sheets in the .xlsx format, we use the XSSF implementation provided by the Apache POI library.

Test Scenario

  1. (a) 🡪 Search for ‘LambdaTest’ on Bing.com
  2. (b) 🡪 Search for ‘LambdaTest Blog’ on Bing.com
  3. Click on the First test result
  4. Assert if the current page title does not match with the expected page title
  5. Append the corresponding test result in the cell next to the test case

Here is the content of the MS Excel File (i.e., Test_1.xls) that contains details of the test scenario:

Implementation

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

package com.DataDrivenFramework;

import java.io.*;

import java.net.MalformedURLException;

import java.net.URL;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.Assert;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class test_DataDrivenFramework

WebDriver driver;

XSSFWorkbook workbook;

Sheet sheet;

Cell cell;

String username = “user-name”;

String access_key = “access-key”;

@BeforeTest

public void init() throws InterruptedException, MalformedURLException

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(“build”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“name”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“platformName”, “OS X Yosemite”);

capabilities.setCapability(“browserName”, “MicrosoftEdge”);

capabilities.setCapability(“browserVersion”,”81.0″);

capabilities.setCapability(“tunnel”,false);

capabilities.setCapability(“network”,true);

capabilities.setCapability(“console”,true);

capabilities.setCapability(“visual”,true);

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”),

capabilities);

System.out.println(“Started session”);

@Test (description = “Testing data input from XLS (i.e. HSSF)”, priority = 1, enabled = true)

public void Test_ddf_hssf_input() throws IOException, InterruptedException

HSSFWorkbook workbook;

String test_url = null;

WebElement lt_link = null;

String exp_title = null;

/* Import Excel Sheet */

File src=new File(“C:\\Folder\\Test_1.xls”);

/* Load the file */

FileInputStream fis = new FileInputStream(src);

/* Load the workbook */

workbook = new HSSFWorkbook(fis);

/* Load the sheet in the workbook */

/* Index = 0 –> Tab – 1 */

sheet = workbook.getSheetAt(0);

for(int counter = 1; counter <= sheet.getLastRowNum(); counter++)

/* Row – 0 –> Contains the site details and search term */

/* Hence, we skip that row */

cell = sheet.getRow(counter).getCell(0);

/* Cell [1,0] contains the test URL */

if (cell.getCellType() == CellType.STRING)

test_url = cell.getStringCellValue();

driver.get(test_url);

/* Cell [1,1] –> Search Term */

cell = sheet.getRow(counter).getCell(1);

if (cell.getCellType() == CellType.STRING)

String search_string = cell.getStringCellValue();

/* Let’s perform the search operation */

try

/* Enter the search term in the Google Search Box */

WebElement search_box = driver.findElement(By.xpath(“//input[@id=’sb_form_q’]”));

search_box.sendKeys(search_string + Keys.ENTER);

Thread.sleep(3000);

if (search_string.equalsIgnoreCase(“LambdaTest”)) {

lt_link = driver.findElement(By.xpath(“//a[.=’Most Powerful Cross Browser Testing Tool Online | LambdaTest’]”));

exp_title = “Most Powerful Cross Browser Testing Tool Online | LambdaTest”;

} else if (search_string.equalsIgnoreCase(“LambdaTest Blog”)) {

lt_link = driver.findElement(By.xpath(“//a[.=’LambdaTest | A Cross Browser Testing Blog’]”));

exp_title = “LambdaTest | A Cross Browser Testing Blog”;

if (lt_link!= null)

lt_link.click();

Thread.sleep(3000);

String curr_window_title = driver.getTitle();

Assert.assertEquals(curr_window_title, exp_title);

/* Write the result in the excel sheet */

/* Write Data in the Result Column */

FileOutputStream fos = new FileOutputStream(src);

String message = “Passed”;

sheet.getRow(counter).createCell(2).setCellValue(message);

workbook.write(fos);

fos.close();

} catch (Exception e) {

System.out.println(e.getMessage());

@AfterClass

public void tearDown()

if (driver != null)

driver.quit();

Code Walkthrough

1. Import the packages that contain the methods and interfaces for performing operations on .xls file

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

2. The method implemented under the @BeforeTest annotation sets the desired browser capabilities. A RemoteWebDriver instance is created with the desired browser capabilities, with the Selenium Grid URL set to the cloud-based Selenium Grid on LambdaTest [ @hub.lambdatest.com/wd/hub ].

10

11

12

@BeforeTest

public void init() throws InterruptedException, MalformedURLException

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(“build”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“name”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“platformName”, “OS X Yosemite”);

capabilities.setCapability(“browserName”, “MicrosoftEdge”);

capabilities.setCapability(“browserVersion”,”81.0″);

capabilities.setCapability(“tunnel”,false);

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”), capabilities);

3. Create a new workbook of type HSSFWorkbook. It will be further used when accessing the Sheet and reading/writing at appropriate cells in the Sheet.

public void Test_ddf_hssf_input() throws IOException, InterruptedException

HSSFWorkbook workbook;

4. Create a Workbook object by referring to the FileInputStream object that points to the location where the Excel File (.xls) is located on the host machine.

File src=new File(“C:\\Folder\\Test_1.xls”);

FileInputStream fis = new FileInputStream(src);

5. Load the Excel Workbook using the FileInputStream object obtained from Step (4).

workbook = new HSSFWorkbook(fis);

6. Using the Workbook object, we access the Sheet at index ‘0’ using the getSheetAt method.

sheet = workbook.getSheetAt(0);

7. Row zero contains the Header (or title) in the sheet. Hence, that row is ignored. Cell (0,0) 🡪 Test URL, Cell (0, 1) 🡪 Search Term, and Cell (0,2) 🡪 Test Result. A for loop starting from 1 to the total number of rows (i.e., 2 in this case) obtained using getLastRowNum method of the Sheet class is run for executing the test scenarios 1(a) and 1(b).

for(int counter = 1; counter <= sheet.getLastRowNum(); counter++)

8. The getRow method returns the logical row number [i.e. 1 for test scenario -1(a) and 2 for test scenario – 1(b)]. Once we have the row number, the getCell(cell-number) method of the HSSFRow object is used for accessing the specific cell.

Shown below are the contents of the cells on Row – 1:

  • Cell (1,0 ) 🡪https://www.bing.com
  • Cell (1,1) 🡪 LambdaTest
  • Cell (1,2) 🡪 Result (Test Status updated post test execution)

cell = sheet.getRow(counter).getCell(0);

9. Cell (1,0) contains the URL under test. Using the Cell obtained from step (8), the getStringCellValue method gets the value of the cell as a String. Next, we navigate to the test URL.

if (cell.getCellType() == CellType.STRING)

test_url = cell.getStringCellValue();

driver.get(test_url);

10. The required search terms are located in the following Cells:

  • Cell (1,1) 🡪 LambdaTest
  • Cell (2,1) 🡪 LambdaTest Blog

The getRow method returns the logical row number. For example, row number 1 represents Test Scenario – 1(a) and row number 2 represents Test Scenario – 1(b). Cell number remains unchanged. Hence it is hard coded to ‘1’. Finally, the search string is retrieved from the Cell using the getStringCellValue() method.

cell = sheet.getRow(counter).getCell(1);

String search_string = cell.getStringCellValue();

11. Now that we have the search string from the previous step, it is entered in the search box, and an Enter key is pressed to initiate the search operation. For test scenario 1(a), the search term is ‘LambdaTest,’ and for scenario 1(b), the search term is ‘LambdaTest Blog.’

Though the search terms for both tests are different, the overall execution path remains unchanged.

WebElement search_box = driver.findElement(By.xpath(“//input[@id=’sb_form_q’]”));

search_box.sendKeys(search_string + Keys.ENTER);

12. Depending on the search term, the link that appears as the first result also changes. A case insensitive string comparison is done with the search term and based on the comparison result, and the top result link is located using the XPath property of the WebElement.

Also Read – XPath In Selenium With Examples

Test Scenario 1(a)

lt_link = driver.findElement(By.xpath(“//a[.=’Most Powerful Cross Browser Testing Tool Online | LambdaTest’]”));

exp_title = “Most Powerful Cross Browser Testing Tool Online | LambdaTest”;

Test Scenario 1(b)

lt_link = driver.findElement(By.xpath(“//a[.=’LambdaTest | A Cross Browser Testing Blog’]”));

exp_title = “LambdaTest | A Cross Browser Testing Blog”;

13. A click operation is performed on the WebElement that points to the first test result on the Bing Search page.

if (lt_link!= null)

lt_link.click();

14. Assert is thrown if the Page Title does not match with the expected page title.

String curr_window_title = driver.getTitle();

Assert.assertEquals(curr_window_title, exp_title);

15. We use the Java FileOutputStream class, an output stream used for writing data in the file. The Excel Workbook, which has the test data (i.e., Path_To_File\File.xls), is opened to write the test result.

  • Test Scenario 1(a) – Test result to be written to Cell (1,2)
  • Test Scenario 1(b) – Test result to be written to Cell (2,2)

Using the required row number, we create a new Cell using the createCell method. In our case, the Cell number where the test result is to be written is 2. Then, in the Cell (inline with the corresponding test scenario), we write the test result (in String format) in the current cell using the setCellValue method offered by the HSSFCell class.

FileOutputStream fos = new FileOutputStream(src);

String message = “Passed”;

sheet.getRow(counter).createCell(2).setCellValue(message);

16. We now write to the OutputStream (i.e., fos) and then close the output stream using the close method offered by the Output Stream.

workbook.write(fos);

fos.close();

Execution

As seen in the snapshot of the Excel Workbook that contained the test inputs, the test scenarios were executed successfully, and the test result was written in the respective cells in the Sheet.

Read and Write data from & to Excel sheets (.xlsx) in Selenium using Apache POI

For performing CRUD operations on MS Excel sheets in the .xlsx format, we use the XSSF implementation provided by the Apache POI library.

Test Scenario

  1. (a) & 1(b) 🡪 Test URL – https://lambdatest.github.io/sample-todo-app/
  2. Add a new item in the LambdaTest ToDo app

    • Test Scenario 1(a) – Testing on LambdaTest
    • Test Scenario 1(b) – Hello World on LambdaTest
  3. Assert if the new item is not added successfully to the list
  4. Write the test result in the input Excel file

Here is the content of the MS Excel File (i.e., Test_2.xlsx) that contains details of the test scenario:

Important

When using Apache POI (for .xls files) and POI OOXML (for .xlsx files) in the same class, it is important to have poi and poi-ooxml point to the same version in pom.xml. This is because Apache Maven POI dependencies for poi & poi-ooxml pointing to different versions lead to the error java.lang.IncompatibleClassChangeError.

In pom.xml, the dependencies for POI and POI-OOXML point to the same versions (i.e., 4.1.2).

Implementation

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

package com.DataDrivenFramework;

import java.io.*;

import java.net.MalformedURLException;

import java.net.URL;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.Assert;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class test_DataDrivenFramework

WebDriver driver;

XSSFWorkbook workbook;

Sheet sheet;

Cell cell;

String username = “user-name”;

String access_key = “access-key”;

@BeforeTest

public void init() throws InterruptedException, MalformedURLException

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(“build”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“name”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“platformName”, “OS X Yosemite”);

capabilities.setCapability(“browserName”, “MicrosoftEdge”);

capabilities.setCapability(“browserVersion”,”81.0″);

capabilities.setCapability(“tunnel”,false);

capabilities.setCapability(“network”,true);

capabilities.setCapability(“console”,true);

capabilities.setCapability(“visual”,true);

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”),

capabilities);

System.out.println(“Started session”);

@Test (description = “Testing data input from XLSX (i.e. XSSF)”, priority = 2, enabled = true)

public void Test_ddf_xssf_input() throws IOException, InterruptedException

XSSFWorkbook workbook;

/* Import the Excel Sheet */

File src=new File(“C:\\Folder\\Test_2.xlsx”);

/* Load the file */

FileInputStream fis = new FileInputStream(src);

/* Load the workbook */

workbook = new XSSFWorkbook(fis);

/* The sheet is in Tab-0 */

sheet = workbook.getSheetAt(0);

for(int counter = 1; counter <= sheet.getLastRowNum(); counter++)

/* Skip Row – 0 */

cell = sheet.getRow(counter).getCell(0);

/* Cell [1,0] contains the test URL */

if (cell.getCellType() == CellType.STRING)

String test_url = cell.getStringCellValue();

driver.get(test_url);

/* Cell [1,1] –> Search Term */

cell = sheet.getRow(counter).getCell(1);

if (cell.getCellType() == CellType.STRING)

String new_item = cell.getStringCellValue();

try

/* Let’s mark done first two items in the list. */

driver.findElement(By.name(“li1”)).click();

driver.findElement(By.name(“li2”)).click();

/* Get the item to be added from the sheet */

/* Let’s add an item in the list. */

driver.findElement(By.id(“sampletodotext”)).sendKeys(new_item);

driver.findElement(By.id(“addbutton”)).click();

/* Let’s check that the item we added is added in the list. */

String enteredText = driver.findElement(By.xpath(“/html/body/div/div/div/ul/li[6]/span”)).getText();

if (enteredText.equals(new_item))

System.out.println(“Demonstration is complete”);

String status = “passed”;

/* Write the result in the excel sheet */

/* Write Data in the Result Column */

FileOutputStream fos = new FileOutputStream(src);

String message = “Passed”;

sheet.getRow(counter).createCell(2).setCellValue(message);

workbook.write(fos);

fos.close();

catch (Exception e)

System.out.println(e.getMessage());

@AfterClass

public void tearDown()

if (driver != null)

driver.quit();

Code Walkthrough

1. Create an object of XSSFWorkbook. This object will be further used when accessing the Sheet and reading/writing at appropriate cells in the Sheet.

XSSFWorkbook workbook;

2. Create a Workbook object by referring to the FileInputStream object that points to the location where the Excel File (.xlsx) is located on the host machine.

File src=new File(“C:\\Folder\\Test_2.xlsx”);

FileInputStream fis = new FileInputStream(src);

3. Load the Excel Workbook using the FileInputStream object obtained from Step (2).

workbook = new XSSFWorkbook(fis);

4. Using the Workbook object, we access the Sheet at index ‘0’ using the getSheetAt method.

sheet = workbook.getSheetAt(0);

5. Like the earlier test, which demonstrated the usage of the HSSF Workbook, row (0) also contains the title of the fields (i.e., Test URL, Item to Add, and Result). Hence, we exclude Row (0) from the test execution.

A for loop is run from rows 1 to sheet.getLastRowNum() [which equates to ‘2’ in our case] so that the two test scenarios in the sheet can be executed one after the other.

for(int counter = 1; counter <= sheet.getLastRowNum(); counter++)

6. The getRow method returns the logical row number [i.e. 1 for test scenario -1(a) and 2 for test scenario – 1(b)]. Now that we have the row number, the getCell(cell-number) method of the XSSFRow is used for accessing the specific cell.

Shown below are the contents of the cells on Row – 1:

  • Cell (1,0 ) 🡪 https://lambdatest.github.io/sample-todo-app/
  • Cell (1,1) 🡪 Testing on LambdaTest
  • Cell (1,2) 🡪 Result (Test Status updated post-test execution)

Cell (1,0) contains the URL under test. The getStringCellValue method gets the value of the cell as a String. Next, we navigate to the test URL.

cell = sheet.getRow(counter).getCell(0);

/* Cell [1,0] contains the test URL */

if (cell.getCellType() == CellType.STRING)

String test_url = cell.getStringCellValue();

driver.get(test_url);

7. New items to be added are located in the following Cells:

  • Cell (1, 1) 🡪 Testing on LambdaTest
  • Cell (2,1) 🡪 Hello World on LambdaTest

Row number 1 represents Test Scenario – 1(a) and row number 2 represents Test Scenario – 1(b). Cell number remains unchanged; hence it is hard coded to ‘1’. The new items to be added to the ToDo list are retrieved from the Cell using the getStringCellValue() method.

cell = sheet.getRow(counter).getCell(1);

if (cell.getCellType() == CellType.STRING)

String new_item = cell.getStringCellValue();

8. First two items in the ToDo list are marked as ‘Done’ by locating the respective WebElement using the Name property and then performing the click() operation on that WebElement.

driver.findElement(By.name(“li1”)).click();

driver.findElement(By.name(“li2”)).click();

Also Read – How To Use Name Locator In Selenium Automation Scripts?

9. New entry to the ToDo list is added by locating the WebElement using the ID property and using the sendKeys method for entering the new entry in the text box.

The Add Button on the page is located using the ID property, and click operation is performed on the button for adding the new entry to the ToDo list.

driver.findElement(By.id(“sampletodotext”)).sendKeys(new_item);

driver.findElement(By.id(“addbutton”)).click();

Also Read – Making The Move With ID Locator In Selenium WebDriver

10. The content of the newly added item is fetched using the getText() method in Selenium. If the newly added item equals the expected item, the test is considered as ‘Passed.’

String enteredText = driver.findElement(By.xpath(“/html/body/div/div/div/ul/li[6]/span”)).getText();

if (enteredText.equals(new_item))

System.out.println(“Demonstration is complete”);

String status = “passed”;

11. The Java FileOutputStream class is used for writing the data in the file. Then, the Excel Workbook with the test data (i.e., Path_To_File\File.xlsx) is opened to write the test result.

  • Test Scenario 1(a) – Test result to be written to Cell (1,2)
  • Test Scenario 1(b) – Test result to be written to Cell (2,2)

The test result for the respective tests is written in the corresponding Cells as a String Value. The setCellValue method writes the test result in the Cell.

FileOutputStream fos = new FileOutputStream(src);

String message = “Passed”;

sheet.getRow(counter).createCell(2).setCellValue(message);

12. We now write to the OutputStream (i.e. fos). Post the write operation, the close method is invoked for closing the OutputStream.

workbook.write(fos);

fos.close();

Execution

As seen in the Excel Workbook snapshot containing the test inputs, test scenarios are executed successfully, and test results are written in the correct Cells in the Sheet.

Data Driven Framework in Selenium using TestNG DataProvider with Excel

DataProvider in TestNG is popularly used with MS Excel, where the data to be supplied in the DataProvider is read from an Excel sheet. This approach is primarily useful when the test has to be performed against a massive amount of test data. You can refer to DataProviders in TestNG for a quick recap on the topic.

Test Scenario

  1. (a) 🡪 Search for ‘LambdaTest’ on Google
  2. (b) 🡪 Search for ‘LambdaTest Blog’ on Google
  3. Click on the First test result
  4. Assert if the current page title does not match with the expected page title
  5. Append the corresponding test result in the cell next to the test case

To get started, we create a test data set in an Excel Sheet. The first column contains the Search Term and the second column contains the Expected Page Title after the search is executed.

Implementation

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

package com.DataDrivenFramework;

import java.io.*;

import java.net.MalformedURLException;

import java.net.URL;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.openqa.selenium.*;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.Assert;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class test_DataDrivenFramework

WebDriver driver;

XSSFWorkbook workbook;

Sheet sheet;

Cell cell;

String username = “user-name”;

String access_key = “access-key”;

@BeforeTest

public void init() throws InterruptedException, MalformedURLException

DesiredCapabilities capabilities = new DesiredCapabilities();

capabilities.setCapability(“build”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“name”, “[Java] Data Driven Framework in Selenium WebDriver”);

capabilities.setCapability(“platformName”, “OS X Yosemite”);

capabilities.setCapability(“browserName”, “MicrosoftEdge”);

capabilities.setCapability(“browserVersion”,”81.0″);

capabilities.setCapability(“tunnel”,false);

capabilities.setCapability(“network”,true);

capabilities.setCapability(“console”,true);

capabilities.setCapability(“visual”,true);

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”),

capabilities);

System.out.println(“Started session”);

@DataProvider(name=”dataset”)

public Object[][] getExcelData()

Object[][] arrObj = getExData(“C:\\Folder\\Test_4.xlsx”,”TestData”);

return arrObj;

public String[][] getExData(String fileName, String sheetName)

String[][] data = null;

try

FileInputStream fis = new FileInputStream(fileName);

XSSFWorkbook workbook = new XSSFWorkbook(fis);

XSSFSheet sheet = workbook.getSheet(sheetName);

XSSFRow row = sheet.getRow(0);

int noOfRows = sheet.getPhysicalNumberOfRows();

int noOfCols = row.getLastCellNum();

Cell cell;

data = new String[noOfRows – 1][noOfCols];

for(int outer_cnt = 1; outer_cnt < noOfRows; outer_cnt++)

for(int inner_cnt = 0; inner_cnt < noOfCols; inner_cnt++)

row = sheet.getRow(outer_cnt);

cell= row.getCell(inner_cnt);

data[outer_cnt – 1][inner_cnt] = cell.getStringCellValue();

System.out.println(data[outer_cnt – 1][inner_cnt]);

catch (Exception e)

System.out.println(“The exception is: ” +e.getMessage());

return data;

@Test(dataProvider =”dataset”, description = “Data Driven framework using Data Provider”, priority = 3, enabled = true)

public void Test_ddf_dataprovider_excel(String search_string, String expected_title) throws IOException, InterruptedException

String test_url = “https://www.google.com”;

WebElement lt_link = null;

driver.manage().window().maximize();

driver.get(test_url);

Thread.sleep(3000);

try

/* Enter the search term in the Google Search Box */

WebElement search_box = driver.findElement(By.xpath(“//input[@name=’q’]”));

search_box.sendKeys(search_string);

search_box.submit();

Thread.sleep(3000);

/* Click on the first result which will open up the LambdaTest homepage */

if (search_string.equalsIgnoreCase(“LambdaTest”))

lt_link = driver.findElement(By.xpath(“//span[.=’LambdaTest: Most Powerful Cross Browser Testing Tool Online’]”));

else if (search_string.equalsIgnoreCase(“LambdaTest Blog”))

lt_link = driver.findElement(By.xpath(“//span[.=’A Cross Browser Testing Blog – LambdaTest’]”));

lt_link.click();

Thread.sleep(3000);

String curr_window_title = driver.getTitle();

Assert.assertEquals(curr_window_title, expected_title);

catch (Exception e)

System.out.println(e.getMessage());

@AfterClass

public void tearDown()

if (driver != null)

driver.quit();

Code WalkThrough

  • getExData Method

1. An object of Workbook is created by referring to the FileInputStream object that points to the location where the Excel File (.xlsx) is located on the host machine.

The object of type XSSFWorkbook will be further used for accessing the Sheet and the various Cells in the Sheet.

FileInputStream fis = new FileInputStream(fileName);

XSSFWorkbook workbook = new XSSFWorkbook(fis);

2. We get the Sheet using the getSheet method that takes the Sheetname as the input argument. In our case, the test data is available in the sheet with the name ‘TestData’; hence, the same is passed to the getSheet method.

Once inside the Sheet, we read the first using the getRow method, which returns an object of type XSSFRow.

XSSFSheet sheet = workbook.getSheet(sheetName);

XSSFRow row = sheet.getRow(0);

3. We get the total number of rows and columns (or Cells) using the getPhysicalNumberOfRows method in XSSFSheet class and getLastCellNum method in XFFSRow class.

int noOfRows = sheet.getPhysicalNumberOfRows();

int noOfCols = row.getLastCellNum();

In our case, the number of Rows & Columns are 3 & 2, respectively.

4. We create a new 2D String array of [2] [2] dimensions

data = new String[noOfRows – 1][noOfCols];

5. In a nested for loop (outer-count 🡪 1.. no of rows, inner-count 🡪 0.. no of columns), we fetch the current row using the getRow method. The getCell method returns the current column.

Now that we have the row and column, the data in that particular cell is read using the getStringCellValue() method provided by the Cell class. Since the Row ‘0’ contains the title (i.e., Keyword, Expected Title), we start reading from the first row.

  • First for loop run
  • Second for loop run

row = 1, cell = 0, data [0] [0] = LambdaTest (i.e. Cell [1] [0])row = 1, cell = 1, data [0] [1] = Most Powerful Cross Browser Testing Tool Online | LambdaTest (i.e. Cell [1] [1])

row = 2, cell = 0, data [1] [0] = LambdaTest Blog (i.e. Cell [2] [0])row = 2, cell = 1, data [1] [1] = LambdaTest | A Cross Browser Testing Blog (i.e. Cell [2] [1])

10

for(int outer_cnt = 1; outer_cnt < noOfRows; outer_cnt++)

for(int inner_cnt = 0; inner_cnt < noOfCols; inner_cnt++)

row = sheet.getRow(outer_cnt);

cell= row.getCell(inner_cnt);

data[outer_cnt – 1][inner_cnt] = cell.getStringCellValue();

System.out.println(data[outer_cnt – 1][inner_cnt]);

6. Return the 2D array (i.e., data[][]) that we populated with the values from the Sheet [in Step (5)]


return data;

  • getExcelData

In this method, we create a DataProvider method that uses the getExData method that returns a 2D object created by reading the required Cell values from the Excel Sheet.

@DataProvider(name=”dataset”)

public Object[][] getExcelData()

Object[][] arrObj = getExData(“C:\\Folder\\Test_4.xlsx”,”TestData”);

return arrObj;

  • Test_ddf_dataprovider_excel

1. This test method uses the ‘dataset’ DataProvider that returns a 2D object containing the search string and expected page title.

@Test(dataProvider =”dataset”, description = “Data Driven framework using Data Provider”, priority = 3, enabled = true)

public void Test_ddf_dataprovider_excel(String search_string, String expected_title) throws IOException, InterruptedException

2. Once we navigate to the test URL (i.e., Google Homepage), enter the search term in the search box using the sendKeys method in Selenium. The search box is located using the findElement method in Selenium which uses the XPath property for locating the search box Web Element.

WebElement search_box = driver.findElement(By.xpath(“//input[@name=’q’]”));

search_box.sendKeys(search_string);

3. Trigger the search using the submit() method.

search_box.submit();

4. Perform a case-insensitive comparison of the Search String (i.e. LambdaTest/LambdaTest Blog) and accordingly locate the first link using the findElement method with the WebElement’s XPath property.

if (search_string.equalsIgnoreCase(“LambdaTest”))

lt_link = driver.findElement(By.xpath(“//span[.=’LambdaTest: Most Powerful Cross Browser Testing Tool Online’]”));

else if (search_string.equalsIgnoreCase(“LambdaTest Blog”))

lt_link = driver.findElement(By.xpath(“//span[.=’A Cross Browser Testing Blog – LambdaTest’]”));

5. Now that the link is located click on the link to navigate to the resultant page.


lt_link.click();

6. Get the current page title using the getTitle() method of Selenium WebDriver. Assert if the current page title does not match the expected title.

String curr_window_title = driver.getTitle();

Assert.assertEquals(curr_window_title, expected_title);

Execution

Below is the execution snapshot from the IntelliJ IDE, which indicates that the data from the external data set (i.e., Excel Sheet) was read successfully. As a result, the DataProvider in TestNG was able to use that data for performing the search operation on Google.

Selenium Cucumber Java BDD Framework 5 - Parameterization & Data Driven Testing
Selenium Cucumber Java BDD Framework 5 – Parameterization & Data Driven Testing

Download JAR

Step 1 − Navigate to the URL – https://poi.apache.org/download.html and download the ZIP format.

Step 2 − Click on the Mirror Link to download the JAR’s.

Step 3 − Unzip the contents to a folder.

Step 4 − Unzipped contents would be displayed as shown below.

Step 5 − Now create a new project and add all the ‘External JARs’ under ‘poi-3.10.FINAL’ folder.

Step 6 − Now add all the ‘External JARs’ under the ‘ooxml-lib’ folder.

Step 7 − Now add all the ‘External JARs’ under the ‘lib’ folder.

Step 8 − The Added JAR is displayed as shown below.

Step 9 − The Package Explorer is displayed as shown below. Apart from that, add ‘WebDriver’ related JAR’s

Conclusion

Data-driven testing is an amazing approach to improve your efficiency in highly repetitive test scenarios. You can either build a data-driven testing framework from scratch using Selenium and libraries, which is highly customizable for specific scenarios, but once those scripts are broken, maintaining them is quite a daunting task. Or, you can go with an automated testing tool that comes with a prebuilt data-driven testing framework that you can use right away.

What is Data Driven Testing? Learn to create Framework

Data Driven Testing is a software testing method in which test data is stored in table or spreadsheet format. Data driven testing allows testers to input a single test script that can execute tests for all test data from a table and expect the test output in the same table. It is also called table-driven testing or parameterized testing.

SELENIUM : What are the different types of frameworks in Selenium? SDET Automation Testing Interview
SELENIUM : What are the different types of frameworks in Selenium? SDET Automation Testing Interview

Tại sao lại sử dụng Data Driven Testing ?

Khi bạn cần kiểm tra một kịch bản với hàng trăm bộ test dữ liệu bạn sẽ có 3 cách tiếp cận khác nhau

  1. Tạo 100 trăm kịch bản cho 100 trăm bộ test data và chạy mỗi bộ 1 lần
  2. Tạo một kịch bản test và với mỗi bản data lại test 1 lần
  3. Tạo một kịch bản test và gôm tất cả các dữ liệu thành 1 file và chỉ chạy 1 lần tất cả các dữ liệu trong file lưu trữ Cách thứ 3 chính là cách tiếp cận của Data- Driven framework để giảm thiểu thời gian và các công việc của kiểm thử viên phải làm

Data-driven testing framework in Selenium

Selenium can be used to create a data-driven testing framework. Leveraging Selenium, you can create the backbone for efficient and scalable data-driven testing, enabling your team to seamlessly manage test data, thereby enhancing the reliability and maintainability of automated tests.

The key components of this framework include:

  • Test script: Test scripts are the core of the automation process and should be designed to be reusable and independent of specific data values. Specifically, these are the Selenium WebDriver scripts that interact with the web application under test.
  • Test data: Test data includes the input values, expected results, and any other data required for test execution. This is the dynamic element of the framework and can be stored in various formats, including CSV files, Excel spreadsheets, or databases. Each row in the data source represents a unique set of inputs for your test script.
  • Parameterization: Test data is fed into the test script as parameters. These parameters replace the hard-coded values in the script, allowing it to adapt to different scenarios. To illustrate, if you are testing a login page, parameters could include usernames and passwords.
  • Reporting and logging: To monitor and report the test execution, comprehensive logging and reporting mechanisms are required, which can help in tracking test execution, identifying failures, and generating meaningful reports for analysis.

Overall, a data-driven framework enhances test automation. Whether you’re testing web applications, APIs, or mobile apps, mastering the data-driven framework will undoubtedly elevate your Selenium test automation game.

Read More: 6 Common Types of Software Test Automation Frameworks

Data Driven Framework Made Easy (Creating and Using) - Selenium Java POI API
Data Driven Framework Made Easy (Creating and Using) – Selenium Java POI API

What is Apache POI

Apache POI (Poor Obfuscation Implementation) is an open-source library developed and distributed by the Apache Software Foundation. It is the most commonly used API for realizing data driven tests in Selenium.

The API provided by the library files in Apache POI lets the user manipulate Microsoft Documents – Excel files (*.xls, *.xlsx), Doc files (*.doc), and more. In a nutshell, Apache POI is the Java Excel solution that lets you read/write/modify data from/to external data feeds.

Also Read – Everything You Need To Know about API testing

Handling Excel Files using Apache POI

The Apache POI consists of classes and methods that simplify processing MS Excel sheets in Java. Therefore, it is important to be well-versed with the common terminologies used when working with MS Excel.

  • Workbook – A Workbook in Microsoft Excel is primarily used to create and maintain the Spreadsheet (or Sheet). It can contain one or more spreadsheets.
  • Sheet – A Sheet in a workbook is a page made up of Rows and Columns.
  • Row – A Row in a Sheet runs horizontally and is represented as a collection of Cells.
  • Cell – A Cell in a Sheet is represented by a Row and Column combination. Data entered by the user is stored in a cell. For example – Cell (0, 1) indicates the data is stored in Row: 0 and Column: 1.

The Apache POI library provides an HSSF implementation for performing operations on MS Excel files in the .xls format. On the other hand, XSSF implementation in Apache POI lets you perform operations on MS Excel Files in the .xlsx format.

Handling .xls Files using Apache POI

For reading .xls files, HSSF implementation is provided by the Apache POI library. The methods used for performing operations on the .xls files are available in the classes that belong to the org.apache.poi.hssf.usermodel package.

Here are the important classes & methods in the org.apache.poi.hssf.usermodel package that helps in performing CRUD operations on .xls files:

  • HSSFWorkbook – Represents a Workbook in the .xls format
  • HSSFSheet – Represents a Sheet in the .xls workbook
  • HSSFRow – Represents a Row in the .xls file
  • HSSFCell – Represents a Cell in the Row of the .xls file

Using Apache POI with Java and TestNG makes it easy to manage the Apache POI Selenium Maven dependency in the pom.xml file. You could refer to our detailed blog on Maven for Selenium Testing for a quick recap on Maven with Selenium.

Here is the Maven dependency for using the Apache POI library to access .xls files in Java:

[….]


org.apache.poi


poi


4.1.2

[….]

Handling .xlsx Files using Apache POI

For reading .xlsx files, XSSF implementation is provided by the Apache POI library and the org.apache.poi.xssf.usermodel package contains classes and methods that let you achieve the same.

Here are the important classes & methods in the org.apache.poi.xssf.usermodel package that helps in performing CRUD operations on .xlsx files:

  • XSSFWorkbook – Represents a Workbook in the .xlsx format
  • XSSFSheet – Represents a Sheet in the .xlsx workbook
  • XSSFRow – Represents a Row in the .xlsx file
  • XSSFCell – Represents a Cell in the Row of the .xlsx file

Here is the Maven dependency for using the Apache POI library to access .xlsx files in Java:

10

[….]


org.apache.poi


poi-ooxml


4.1.2


test

[….]

Shown below is the Apache POI Selenium Maven dependency that would download the libraries for accessing the .xls and .xlsx Excel formats:

10

11

12

13

14

15

16

17

[….]


org.apache.poi


poi


4.1.2


org.apache.poi


poi-ooxml


4.1.2


test

[….]

The Enum CellType contains the different field types that can be accessed to get the Cell Type (i.e., String, Boolean, etc.).

Here are the following fields in a Cell (that is accessible via the getCellType() method):

  • CellType. _NONE – Represents a state before the initialization or the lack of a concrete type
  • CellType.NUMERIC – Represents numeric data in a Cell
  • CellType.STRING – Represents String in a Cell
  • CellType.FORMULA – Represents Formula result that is applied on the Cell
  • CellType.BLANK – Represents an Empty Cell
  • CellType.BOOLEAN – Represents a Boolean value in a Cell
  • CellType.ERROR – Represents an Error value in a Cell

At the time of writing this blog, the latest version of Apache POI was 4.1.2. It is recommended to look at the methods, interfaces, classes, enums, and deprecations in the Apache POI 4.1 documentation. For example, the getCellTypeEnum() will be removed in Apache POI 4.2 and the same has been renamed to getCellType(). It is essential to use the latest (or up to date) classes and APIs so that the implementation works flawlessly even when we migrate to future versions of Apache POI (e.g., 4.2, 5.0)

Here is the pictorial view of the classes and interfaces that are widely used when accessing .xls and .xlsx files using Java and Apache POI:

Now that we have covered the essential fundamentals of the Data Driven Framework in Selenium WebDriver, we take a look at how Apache POI can be used with Maven and TestNG to realize data driven testing in Selenium.

Excelling with automated testing is a vital and competent skill today and can present you with a viable future. TestNG will equip you with the right skill set needed to begin your journey as an automation expert. TestNG certification from LambdaTest can help you take your test engineering skills to the next level.

Here’s a short glimpse of the TestNG certification offered by LambdaTest:

What is an Automation Framework?

An automation testing framework is a set of guidelines or rules used for creating and designing test cases. The guidelines include coding standards, object repositories, test-data handling methods, processes to store test results, or any other information on how to access external resources.

A tester can always write tests without a framework, it is not a mandatory step but using an organized framework provides additional benefits like increased code re-usage, higher portability, reduced script maintenance cost, and higher code readability. It also helps the team to write down the test script in a standard format. Using an automation testing framework, efficient design and development of automated test scripts enable and it ensures reliable analysis of issues or bugs for the system or application under test. The below section lists a few of the important benefits which justifies the need for an automation testing framework:

Why do we need an Automation testing framework?

It is important to use a framework for automated testing as it improves the automation testing team’s efficiency and test development speed. Some of the benefits of using the automation framework are as below:

  • Standard Format for all the tests
  • Improved test efficiency
  • Lower script maintenance costs
  • Maximum test coverage
  • Reusability of code
  • Efficient Test Data Management

What are the different types of automation frameworks in Selenium?

When testing an application using Selenium WebDriver, there are three main types of frameworks that we can use to create automated tests for any web application:

  • Data Driven Test Framework.
  • Keyword Driven Test Framework.
  • Hybrid Test Framework.

Each of these frameworks has its own architecture and different benefits and disadvantages. When building out a test plan, it’s important to choose the framework that is right for you.

  • Data Driven Testing Framework is used to separate the test script from the test data. You can test the same script with multiple sets of data. We will discuss this framework in detail in the following topics.
  • Keyword Driven Testing Framework is an extension of the Data Driven framework. It allows storing a set of code called ‘keywords’ in a separate code file, externally from the test script. We can reuse these keywords across multiple test scripts. For details refer -Keyword Driven Framework
  • Hybrid Driven Framework is a combination of both the Data-Driven and Keyword-Driven framework. Here, the keywords, as well as the test data, are external. We maintain Keywords in a separate file and test data in excel file or CSV files or database. For details refer – Hybrid Framework.

Here, in this article, Let us take a deep dive into the Data Driven Test Framework.

What is Data Driven Framework?

Generally, when we test an application manually, we run the same scenario for multiple test data. Additionally, we keep the same test data in some files like Excel Files, Text Files, CSV Files, or any database. The same is true for automation also, where we would like to run the same test scenario for multiple test data. Let’s say you have written an automation script to fill the student registration form on the ToolsQA Demo site. There can be many students for registration, the only thing that is differentiating in the code is input values (Name, Address, Phone, Gender, etc..). Will you write a separate script for every student to register? Is there a way, we can reuse the code and only change the student data?

Yes, this is where the Data Driven Framework comes into play and makes the test scripts work properly for different sets of test data. It saves time to write additional code. It’s like write once and run many times mechanism as you can run the same Selenium script multiple times.

In simple words, we use the Data Driven Framework when we have to execute the same script with multiple sets of test data, whose storage is at a different place and not present inside the test script. Any changes done to the data will not impact the code of the test.

What are the benefits of using the Data Driven Testing Framework?

Following are a few of the major benefits which a QA can reap when he/she develops the automation framework using the Data-Driven technique:

  • Test cases can be modified without much changes to code.
  • It allows testing the application with multiple sets of data values, especially during regression testing.
  • It helps us to separate the logic of the test cases/scripts from the test data.

One of the most commonly used, data sources for the test is Microsoft Excel Sheets. We can maintain the data in excel sheets and use them in the test script. Let’s see how we can create a Data Driven UI automation framework by reading the test data from Excel files.

Data Driven Framework in Selenium(with Example Code) |. Poi Java Tutorial | Day 26
Data Driven Framework in Selenium(with Example Code) |. Poi Java Tutorial | Day 26

Parameterization

For demonstration, we will parameterize the percent calculator test.

Step 1 − We will parameterize all the inputs required for percent calculator using Excel. The designed Excel is shown below.

Step 2 − Execute all the percent calculator functions for all the specified parameters.

Step 3 − Let us create generic methods to access the Excel file using the imported JARs. These methods help us get a particular cell data or to set a particular cell data, etc.

import java.io.*; import org.apache.poi.xssf.usermodel.*; public class ExcelUtils { private XSSFSheet ExcelWSheet; private XSSFWorkbook ExcelWBook; //Constructor to connect to the Excel with sheetname and Path public Excelutils(String Path, String SheetName) throws Exception { try { // Open the Excel file FileInputStream ExcelFile = new FileInputStream(Path); // Access the required test data sheet ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); } catch (Exception e) { throw (e); } } //This method is to set the rowcount of the excel. public int excel_get_rows() throws Exception { try { return ExcelWSheet.getPhysicalNumberOfRows(); } catch (Exception e) { throw (e); } } //This method to get the data and get the value as strings. public String getCellDataasstring(int RowNum, int ColNum) throws Exception { try { String CellData = ExcelWSheet.getRow(RowNum).getCell(ColNum).getStringCellValue(); System.out.println(“The value of CellData ” + CellData); return CellData; } catch (Exception e) { return “Errors in Getting Cell Data”; } } //This method to get the data and get the value as number. public double getCellDataasnumber(int RowNum, int ColNum) throws Exception { try { double CellData = ExcelWSheet.getRow(RowNum).getCell(ColNum).getNumericCellValue(); System.out.println(“The value of CellData ” + CellData); return CellData; } catch (Exception e) { return 000.00; } } }

Step 4 − Now add a main method which will access the Excel methods that we have developed.

public class xldemo { public static void main(String[] args) throws Exception { ExcelUtils dd = new ExcelUtils (“C:\\Book1.xlsx”,”Sheet1″); System.out.println(“The Row count is ” + dd.excel_get_rows()); dd.getCellDataasnumber(1, 1); dd.getCellDataasnumber(1, 2); dd.getCellDataasnumber(1, 3); dd.getCellDataasnumber(2, 1); dd.getCellDataasnumber(2, 2); dd.getCellDataasnumber(2, 3); dd.getCellDataasnumber(3, 1); dd.getCellDataasnumber(3, 2); dd.getCellDataasnumber(3, 3); } }

Advantages of Data-Driven testing

Data-Driven offer many advantages some of them are:

  1. Allows to test application with multiple sets of data values during Regression testing
  2. Test data and verification data can be organized in just one file, and it is separate from the test case logic.
  3. Base on the tool, it is possible to have the test scripts in a single repository. This makes the texts easy to understand, maintain and manage.
  4. Actions and Functions can be reused in different tests.
  5. Some tools generate test data automatically. This is useful when large volumes of random test data are necessary, which helps to save the time.
  6. Data-driven testing can perform any phase of the development. A data-driven test cares are generally merged in the single process. However, it can be used in multiple test cases.
  7. Allows developers and testers to have clear separation for the logic of their test cases/scripts from the test data.
  8. The same test cases can be executed several times which helps to reduce test case and scripts.
  9. Any changes in the test script do not effect the test data
Selenium Real time Project Framework #7 – Implement Data-driven
Selenium Real time Project Framework #7 – Implement Data-driven

Nhược điểm của Data- Driven testing

  1. Chất lượng của quá trình test phụ thuộc vào kỹ năng test tự tộng và thực hiện của team
  2. Sẽ mất một khoảng thời gian dài để đọc và tìm kiếm nếu bộ test dữ liệu có kích thước lớn

All rights reserved

Are you having difficulty in maintaining the huge sets of test cases for your application? Is the test data scattered across various test scripts? Do you have to maintain separate test scripts for every test environment and then search across all scripts if one value changes in the test data? It is time-taking and hell of an effort, isn’t it? We all wish the test cases are consistent and written in a uniform manner, following a set of rules like we have traffic rules and everyone tries to follow the same when on road. This is where data driven framework comes into play.

You can also make your test cases adhere to a uniform pattern and style, frame guidelines for your peers working on the application, to write the scripts based on the framed rules. In test automation, we can achieve all this using the Data Driven Framework. Let’s understand how we can create a Data Driven Testing Framework for automating a web application using Selenium WebDriver, by covering the details in the following topics:

  • What is an Automation framework?

    • Why do we need an Automation testing framework?
    • What are the different types of automation frameworks in Selenium?
  • What is Data Driven Framework?

    • Also, what are the benefits of using the Data Driven Testing Framework?
  • How to create a Data Driven Framework in Selenium using Apache POI?

Data Driven Framework in Selenium

By Neha Vaidya, Community Contributor – February 8, 2023

As code is added, the number of tests must be increased to ensure that the new code works smoothly. This situation can easily become burdensome. Eventually, testers may give up, reducing testing and opening the path to defective code. With data-driven tests, it is possible to avoid such a scenario.

This article covers why data-driven tests are important. It will discuss steps on how to data-drive your tests, as well as some dos and don’ts.

Why Data Driven Tests important?

There are two main benefits to this:

  • They reduce the cost of adding new tests and changing them when your business rules change. This is done by creating parameters for different scenarios, using data sets that the same code can run against.
  • They help to identify what data is most important for tested behavior. By separating first-class scenario data into parameters, it becomes clear what matters most to the test. This makes it easy to remember how something works when developers need to change it.

What is Data Driven Testing Framework in Selenium?

Data Driven framework is used to drive test cases and suites from an external data feed. The data feed can be data sheets like xls, xlsx, and csv files.

A Data Driven Framework in Selenium is a technique of separating the “data set” from the actual “test case” (code). Since the test case is separated from the data set, one can easily modify the test case of a particular functionality without making changes to the code.

For example, if one has to modify the code for login functionality, they can modify just the login functionality instead of having to modify any other feature dependent on the same code.

One can easily increase the number of test parameters by adding more username and password fields to the excel file (or other sources). Know more about different types of test driven development with the help of this article on TDD vs BDD.

Now let’s understand how to create a test case using a Data Driven Framework.

Data Driven Testing Example

This example will demonstrate how to read the data from excel files and perform data driven testing using Selenium. WebDriver does not directly support data reading of excel files. Therefore, one needs to use a plugin such as Apache POI for reading/writing on any Microsoft office document.

  • To download Apache POI Jar files click here. Download the zip file or tar file as per requirement and place them along with the set of Selenium JARs and configure your build path.

Now let’s understand how to write the first test case. An excel file to read the data from the sheet. The user has entered different combinations of username and password in the sheet.

The task here is to enter all the combinations of username and passwords into the login field in order to test the functionality. Let’s see how to do that.

Here, the target is to enter all these combinations of username and password into the Browserstack Sign in page as shown below.

Let’s write a code snippet to read the data files.

Step 1: Go to the Eclipse IDE and create a project. Add all the dependencies for TestNG, Selenium and Apache POI.

Step 2: Create a class file to write the functionality.

import org.openqa.selenium.By; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ExcelExample{ @Test(dataProvider=”testdata”) public void demoClass(String username, String password) throws InterruptedException { System.setProperty(“webdriver.chrome.driver”, “Path of Chrome Driver”); Webdriver driver = new ChromeDriver(); driver.get(”

In the above code, there is a “TestDataExample() method” in which the user has created an object instance of another class named “ReadExcelFile”. The user has mentioned the path to the excel file. The user has further defined a for loop to retrieve the text from the excel workbook. But to fetch the data from the excel file, one needs to write a class file for the same.

Try Running Selenium Tests on Cloud for Free

import java.io.File; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFile{ XSSFWorkbook work_book; XSSFSheet sheet; public ReadExcelFile(String excelfilePath) { try { File s = new File(excelfilePath); FileInputStream stream = new FileInputStream(s); work_book = new XSSFWorkbook(stream); } catch(Exception e) { System.out.println(e.getMessage()); } } public String getData(int sheetnumber, int row, int column){ sheet = work_book.getSheetAt(sheetnumber); String data = sheet.getRow(row).getCell(column).getStringCellValue(); return data; } public int getRowCount(int sheetIndex){ int row = work_book.getSheetAt(sheetIndex).getLastRowNum(); row = row + 1; return row; }

In the code above, the user has used Apache POI libraries to fetch the data from the excel file. Next, it will point to the data present in the excel file and then enter the relevant username and password to the sign in page.

Note: The same thing can be done using a Data provider in TestNG. But to fetch the data from the Excel sheet, the user needs Apache POI jar files.

Note: Please enter one valid credential to test.

Advantages of Data Driven Testing Framework

  1. Allows testing of the application with multiple sets of data values during regression testing
  2. Separates the test case data from the executable test script
  3. Allows reusing of Actions and Functions in different tests
  4. Generates test data automatically. This is helpful when large volumes of random test data are necessary
  5. Results in the creation of extensive code that is flexible and easy to maintain
  6. Lets developers and testers separate the logic of their test cases/scripts from the test data
  7. Allows execution of test cases several times which helps to reduce test cases and scripts
  8. It does not let changes in test scripts affect the test data.

By incorporating data-driven testing using Selenium, testers can refine their test cases for more efficient execution. This shortens timelines, makes their lives easier and results in more thoroughly tested and better quality software.

Data-Driven Testing Guide With Selenium And Katalon

Working as a software tester, are you sometimes tired of the repetitive and time-consuming nature of the whole process? If yes, a data-driven framework is exactly what you need.

A data-driven framework in Selenium is an approach to automated testing that separates test scripts from test data, enabling testers to run the same test script with different data inputs. It involves storing test data in external sources like spreadsheets or databases and dynamically feeding this data into Selenium scripts during test execution.

Why is this significant? Imagine effortlessly testing your application across various user inputs, browsers, and platforms, all while reducing maintenance efforts. Data-driven frameworks make data-driven testing a breeze, saving you time and resources, and ultimately enhancing the quality of your software. Say goodbye to repetitive testing and hello to streamlined, data-powered success!

In this article, we’ll explain the concept of a data-driven framework in-depth and then provide you with the code for such a framework in Selenium.

Data-Driven Testing with Selenium Automation
Data-Driven Testing with Selenium Automation

How To Do Data-Driven Testing With Katalon

Katalon Platform is a comprehensive test automation platform that allows you to easily create, manage, execute, and generate reports for test cases across web, desktop, mobile, and APIs. Katalon comes with a data-driven testing framework already built in, so all you have to do is create an account, and download Katalon Studio, which is a productive IDE to generate automated tests without having to write a single line of code.

Download Katalon & Start Testing Within Minutes

Once you’ve downloaded Katalon Studio, launch it. You should see the Katalon Studio interface as below. You can then click the “Create new Test Case” button.

You can craft test cases from the wide variety of keywords we offer (which are essentially code snippets to perform specific actions). Here are just a few examples of them: Navigate to URL, Open Browser, Refresh, Right Click, Scroll, Send Keys, etc.

Read more: Create test cases with Katalon Studio

Here we have created a test case called “Find a place”, which includes the following:

  1. Open browser (Chrome).
  2. Navigate to the URL. In this case we chose Airbnb.
  3. Click on Search.
  4. Enter text for a city.
  5. Click Search.

This test case is put under the DDT with MS Excel Files test suite.

Let’s prepare a data file in Excel with two columns: “City” and “Expected Result”. The values Atlanta, New York, and Tokyo will be dynamically added to the script as we execute.

After that, in the Data File section let’s create new test data called excelfile_100cities. Once done, you should arrive at the test data interface, and you can click Browse to import the Excel file we’ve just created into Katalon Studio.

Once imported, we go back to the DDT With MS Excel Files test suite. Click Add and choose the newly imported Excel to bring it to your test suite. After that, click Map All, and Katalon automatically maps all of the columns in your Excel file to the corresponding variable in your test script.

Finally, click Run, and you’re good to go!

As the test gets executed, you should see that it automatically opens the browser, navigates to Airbnb, searches for the exact location we specify in our Excel file, and checks for the available spaces there.

What’s even better is that once the execution is done, the test results are automatically imported into Katalon TestOps for management and reporting purposes. For more information, you can check out Data-driven testing with Katalon Studio.

You can even watch a detailed guide on how to do data-driven testing at Katalon Academy.

You can see how the process of doing data-driven testing is much more straightforward and simpler than going with the traditional scripted approach. A good advantage that tools have over libraries is that they come with self-healing features, which automatically fix any broken test scripts during regression test runs. If you go with Selenium, you must manually fix each individual broken test script, and that is quite time-consuming. Read more for a Katalon vs. Selenium detailed comparison.

Conclusion

Data-driven testing is an amazing approach to improve your efficiency in highly repetitive test scenarios. You can either build a data-driven testing framework from scratch using Selenium and libraries, which is highly customizable for specific scenarios, but once those scripts are broken, maintaining them is quite a daunting task. Or, you can go with an automated testing tool that comes with a prebuilt data-driven testing framework that you can use right away.

How to work on Data Driven Framework in Selenium Using Apache POI?

Data Driven Framework is one of the most popular Automation Testing Frameworks in the current market. Data Driven automated testing is a method in which the test data set is created in the excel sheet, and is then imported into automation testing tools to feed to the software under test.

Selenium Webdriver is a great tool to automate web-based applications. However, it does not support read and write operations in excel files.

Therefore, we use third party APIs like Apache POI.

What you will learn in this tutorial:

  • What is the data driven framework in Selenium WebDriver using excel example
  • How to read and write data from an excel sheet in Selenium WebDriver using Apache POI

Table of Contents:

What is Apache POI?

Apache POI (Poor Obfuscation Implementation) is an API written in Java to support read and write operations – modifying office files. This is the most common API used for Selenium data driven tests.

There are several ways to implement a Data Driven Framework, and each differs in the effort required to develop the framework and maintenance.

Developing a Data Driven framework in Selenium using POI helps reduce maintenance and improve test coverage thus providing a good return on investment.

Recommended reads:

Why do data drive tests?

Often there might be may be a number of data sets that have to be used to test a feature of an application. Now running the same test with different data manually is time-consuming, error prone and a boring task.

Let us understand this scenario with an example.

Suppose we need to test the login/Register/ Any form with multiple input fields with 100 different data sets.

To test this, you have three different approaches:

1) Create 100 scripts one for each dataset and execute each test one by one.2) Change the data in the script and execute it multiple times.3) Import the data from the excel sheet and execute the script multiple times with different data.

The first two scenarios are laborious, time-consuming – implying low ROI. Hence, we must follow the third approach.

In the third approach, are implementing the Data Driven framework where all our data resides in an excel sheet where it is imported from and used to test the features of the application.

=> Want to learn more about Data Driven Framework? We have a detailed article that you can check here.

What do we need to do to implement the Data Driven Framework?

In order to follow this approach we must have Eclipse and TestNG properly configured.

Once done, we will look at:

  • Various interfaces of Apache POI.
  • Integration of Apache POI in the Eclipse.
  • Read the Data from the Excel Sheet.
  • Send the data to the Excel Sheet.
  • Advantages of using Apache POI with Selenium.

Interface in POI

One of the most remarkable features of Apache POI is that it supports read and write operations on both .xls and .xslx files.

Below mentioned are some of the interfaces of the POI.

  • XSSFWorkbook: Represents workbook in xlsx file.
  • HSSFWorkbook: Represents workbook in xls file.
  • XSSFSheet: Represents a sheet in XLSX file.
  • HSSFSheet: Represents a sheet in XLS file.
  • XSSFRow: Represents a row in a sheet of XLSX file.
  • HSSFRow: Represents a row in a sheet of XLS file.
  • XSSFCell: Represents a cell in a row of XLSX file.
  • HSSFCell: Represents a cell in a row of XLS file.

Fields available in a cell:

  • CELL_TYPE_BLANK: Represents a blank cell.
  • CELL_TYPE_BOOLEAN: Represents a Boolean cell (true or false).
  • CELL_TYPE_ERROR: Represents an error value in a cell.
  • CELL_TYPE_FORMULA: Represents a formula result on a cell.
  • CELL_TYPE_NUMERIC: Represents numeric data in a cell.
  • CELL_TYPE_STRING: Represents string in a cell.

Steps to use Selenium with Apache POI

Let us create an automation script to test the login process of web-based applications.

Here, I have taken LinkedIn as an example.

We import data from an excel sheet and then use it to log into the application and after execution, we write the result in the excel sheet.

We need the following software installed on our system to carry on with the steps to execute the framework:

  • Java JDK 1.7+
  • Eclipse IDE
  • TestNG
  • Selenium jars
  • Microsoft Office / Open Office

Step #1)

First, we need to configure the Eclipse with Apache POI.

Download jar files for Apache POI.

Step #2)

Unzip the jar file and add the following jars to your project and configure them.

  • dom4j-1.6.1.jar
  • poi-3.10-FINAL-20140208.jar
  • poi-ooxml-3.10-FINAL-20140208.jar
  • poi-ooxml-schemas-3.10-FINAL-20140208.jar
  • xmlbeans-2.3.0.jar

Step #3)

After configuring the respective jars, create an excel sheet, enter some data in it and save it as TestData.xlsx at your preferred location.

Step #4)

Now let us follow the sample code to read the data from the excel sheet and use it to login to linkedin.com.

package automationFramework; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author Admin * */ public class ReadWriteExcel { WebDriver driver; WebDriverWait wait; HSSFWorkbook workbook; HSSFSheet sheet; HSSFCell cell; @BeforeTest public void TestSetup() { // Set the path of the Firefox driver. System.setProperty(“webdriver.gecko.driver”, “C:\\Users\\geckodriver.exe”); driver = new FirefoxDriver(); // Enter url. driver.get(“http://www.linkedin.com/”); driver.manage().window().maximize(); wait = new WebDriverWait(driver,30); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void ReadData() throws IOException { // Import excel sheet. File src=new File(“C:\\Users\\Admin\\Desktop\\TestData.xls”); // Load the file. FileInputStream finput = new FileInputStream(src); // Load he workbook. workbook = new HSSFWorkbook(finput); // Load the sheet in which data is stored. sheet= workbook.getSheetAt(0); for(int i=1; i&lt;=sheet.getLastRowNum(); i++) { // Import data for Email. cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id(“login-email”)).sendKeys(cell.getStringCellValue()); // Import data for password. cell = sheet.getRow(i).getCell(2); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id(“login-password”)).sendKeys(cell.getStringCellValue()); } } }

Step #5)

Right click on the test case class and click on Run as –> TestNG Test.

Apache POI imports data from the excel sheet and uses it to log into our application. Now that we have seen how to read data from the excel sheet, let’s look at how to write to the sheet.

package automationFramework; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author Admin * */ public class ReadWriteExcel { WebDriver driver; WebDriverWait wait; HSSFWorkbook workbook; HSSFSheet sheet; HSSFCell cell; @BeforeTest public void TestSetup() { // Set the path of the Firefox driver. System.setProperty(“webdriver.gecko.driver”, “C:\\Users\\geckodriver.exe”); driver = new FirefoxDriver(); // Enter url. driver.get(“http://www.linkedin.com/”); driver.manage().window().maximize(); wait = new WebDriverWait(driver,30); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void ReadData() throws IOException { // Import excel sheet. File src=new File(“C:\\Users\\Admin\\Desktop\\TestData.xls”); // Load the file. FileInputStream finput = new FileInputStream(src); // Load he workbook. workbook = new HSSFWorkbook(finput); // Load the sheet in which data is stored. sheet= workbook.getSheetAt(0); for(int i=1; i&lt;=sheet.getLastRowNum(); i++) { // Import data for Email. cell = sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id(“login-email”)).sendKeys(cell.getStringCellValue()); // Import data for password. cell = sheet.getRow(i).getCell(2); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id(“login-password”)).sendKeys(cell.getStringCellValue()); // Write data in the excel. FileOutputStream foutput=new FileOutputStream(src); // Specify the message needs to be written. String message = “Data Imported Successfully.”; // Create cell where data needs to be written. sheet.getRow(i).createCell(3).setCellValue(message); // Specify the file in which data needs to be written. FileOutputStream fileOutput = new FileOutputStream(src); // finally write content workbook.write(fileOutput); // close the file fileOutput.close(); } } }

Note: If you encounter any problems during this process, please check the following points.

  • Make sure all the mentioned jars are added to the project and are properly configured.
  • Required software is correctly installed.
  • Proper use of an interface with respect to excel files, like HSSF for .xls and XSSF for .xlsx.
  • Valid rows and column indexes are used.
  • The excel file must be closed before execution.
  • Proper classes used for the excel file like XSSF used for .xlsx files and HSSF used for .xls files.

Advantages of using Data Driven Framework

  • Improves test coverage.
  • Re-usability of the code.
  • Less maintenance.
  • Faster Execution.
  • Permits better error handling.

Conclusion

Input/Output from and to a file is a very critical part of the software testing process. Apache POI plays a vital role in making this possible for Selenium Test Automation.

Selenium integration with Apache POI facilitates you to run your script multiple times with different data sets, with all data maintained at a single location. It saves time and maintenance effort on the test script.

About the author: This is a guest post by Vivek, a QA Automation Engineer.

Do you have any queries implementing the data-driven testing framework in Selenium WebDriver using Apache POI? Let us know in the comments section below.

How To Create Data Driven Framework In Selenium

Himanshu Sheth

Posted On: September 28, 2021

123960 Views

30 Min Read

The efficiency of test automation largely depends on how well the ‘functionality under test’ is behaving against different input combinations. For instance, an email provider would have to verify different screens like login, sign-up, etc., by supplying different input values to the scenarios. However, the effort involved in maintaining the test code rises significantly with new functionalities in the web product.

The question that needs to be asked is, “Should changes in the business rules lead to new test scenarios, or can existing test scenarios be extended to suit the needs of the new rules?” This is where Data Driven Framework in Selenium can come in super handy, as it enables the QA engineer to test different scenarios using different data sets. The beauty of the Data Driven Testing Framework in Selenium lies in the fact that there is a clear bifurcation of the test code and test data. The test data is kept in an external data feed like MS Excel Sheets, CSV Files, and more.

In this Selenium Java tutorial, we deep dive into the nuances of data driven tests in Selenium and how the popular Data Driven Framework in Selenium can be used for realizing data driven testing as well as cross browser testing. The demonstration of the Data Driven Framework in Selenium WebDriver is performed using the TestNG framework and Apache POI (Poor Obfuscation Implementation) API in Selenium.

TABLE OF CONTENTS

  • Introduction to Data Driven Testing in Selenium WebDriver
  • Data Driven Framework in Selenium WebDriver
  • What is Apache POI
  • How to create Data Driven Framework in Selenium WebDriver using Apache POI
  • Perform Cross Browser Testing in Selenium using Apache POI
Selenium Webdriver With Java  in Hindi #45 - Data Driven Testing- Apache POI| With Practical
Selenium Webdriver With Java in Hindi #45 – Data Driven Testing- Apache POI| With Practical

How To Do Data-Driven Testing With Katalon

Katalon Platform is a comprehensive test automation platform that allows you to easily create, manage, execute, and generate reports for test cases across web, desktop, mobile, and APIs. Katalon comes with a data-driven testing framework already built in, so all you have to do is create an account, and download Katalon Studio, which is a productive IDE to generate automated tests without having to write a single line of code.

Download Katalon & Start Testing Within Minutes

Once you’ve downloaded Katalon Studio, launch it. You should see the Katalon Studio interface as below. You can then click the “Create new Test Case” button.

You can craft test cases from the wide variety of keywords we offer (which are essentially code snippets to perform specific actions). Here are just a few examples of them: Navigate to URL, Open Browser, Refresh, Right Click, Scroll, Send Keys, etc.

Read more: Create test cases with Katalon Studio

Here we have created a test case called “Find a place”, which includes the following:

  1. Open browser (Chrome).
  2. Navigate to the URL. In this case we chose Airbnb.
  3. Click on Search.
  4. Enter text for a city.
  5. Click Search.

This test case is put under the DDT with MS Excel Files test suite.

Let’s prepare a data file in Excel with two columns: “City” and “Expected Result”. The values Atlanta, New York, and Tokyo will be dynamically added to the script as we execute.

After that, in the Data File section let’s create new test data called excelfile_100cities. Once done, you should arrive at the test data interface, and you can click Browse to import the Excel file we’ve just created into Katalon Studio.

Once imported, we go back to the DDT With MS Excel Files test suite. Click Add and choose the newly imported Excel to bring it to your test suite. After that, click Map All, and Katalon automatically maps all of the columns in your Excel file to the corresponding variable in your test script.

Finally, click Run, and you’re good to go!

As the test gets executed, you should see that it automatically opens the browser, navigates to Airbnb, searches for the exact location we specify in our Excel file, and checks for the available spaces there.

What’s even better is that once the execution is done, the test results are automatically imported into Katalon TestOps for management and reporting purposes. For more information, you can check out Data-driven testing with Katalon Studio.

You can even watch a detailed guide on how to do data-driven testing at Katalon Academy.

You can see how the process of doing data-driven testing is much more straightforward and simpler than going with the traditional scripted approach. A good advantage that tools have over libraries is that they come with self-healing features, which automatically fix any broken test scripts during regression test runs. If you go with Selenium, you must manually fix each individual broken test script, and that is quite time-consuming. Read more for a Katalon vs. Selenium detailed comparison.

Data Driven Framework

Data Driven Framework is an automation testing framework in which input values are read from data files and stored into variables in test scripts. It enables testers to build both positive and negative test cases into a single test. Input data in data driven framework can be stored in single or multiple data sources like .xls, .xml, .csv and databases.

In this tutorial, you will learn

  • What is Data Driven Testing?
  • Why Data Driven Testing?
  • How to create a Data Driven Automation Framework
  • Best practices of Data Driven testing:
  • Advantages of Data-Driven testing
  • Disadvantages of Data Driven testing:

Data Driven Testing is important because testers frequently have multiple data sets for a single test and creating individual tests for each data set can be time-consuming. Data driven testing helps keeping data separate from test scripts and the same test scripts can be executed for different combinations of input test data and test results can be generated efficiently.

Example:

For example, we want to test the login system with multiple input fields with 1000 different data sets.

To test this, you can take following different approaches:

Approach 1) Create 1000 scripts one for each dataset and runs each test separately one by one.

Approach 2) Manually change the value in the test script and run it several times.

Approach 3) Import the data from the excel sheet. Fetch test data from excel rows one by one and execute the script.

In the given three scenarios first two are laborious and time-consuming. Therefore, it is ideal to follow the third approach.

Thus, the third approach is nothing but a Data-Driven framework.

DataProvider In TestNG - Data Driven Framework in Selenium - Part 3
DataProvider In TestNG – Data Driven Framework in Selenium – Part 3

What is Data-driven Testing?

Data-driven testing (DDT) is a testing method where you use different types of test data to run the same test script or test case. Instead of creating separate test scripts for each input data, DDT allows you to reuse your test code. Its primary goal is to validate application behavior under a wide range of input conditions, focusing on executing the same test logic using multiple data sets to ensure the application behaves accurately in different scenarios.

At its core, DDT is a process with the following four steps:

  • Capturing embedded data from external data sources such as spreadsheets, CSV files, or databases.
  • Using available automated test scripts and variables, enter the input data in the AUT (application under test).
  • Making a comparison between actual output with expected results.
  • Executing the same test logic again for each data set.

Imagine testing a login functionality where you want to check various scenarios: valid login, invalid login, login with different user roles, and so on. Instead of writing separate scripts for each scenario, DDT lets you input different usernames and passwords from your data source, automatically running the tests for all combinations.

Data-driven Testing Examples

Imagine that you are the tester of an established e-commerce company. Your goal is to ensure that the checkout process is working as expected, so you want to run a test to see if users can authenticate their account seamlessly on your website. We can immediately see that this test scenario poses several challenges:

  1. How do we ensure that we cover all possible user authentication scenarios, when there are so many variations of email, passwords, social media accounts, etc. to be checked?
  2. Users tend to enter their address in a highly inconsistent manner, so how do we make sure that their address formats are valid so that no issues occur during the shipping process?
  3. What are the conditions for valid/invalid card payments?
  4. What are the promotional codes/coupons available at the moment and how do we make sure that they cause no conflicts with each other?

Those challenges can easily be addressed with data-driven testing. Instead of manually typing in specific values for each scenario (which is essentially a hard-coding approach), we can simply prepare the test data for all of the possible scenarios in one database, with each row of data representing one scenario, then write a script to read test data and execute the test steps.

Selenium with Python Tutorial 26-Data Driven Testing using Microsoft Excel + OpenPyXL Module
Selenium with Python Tutorial 26-Data Driven Testing using Microsoft Excel + OpenPyXL Module

Disadvantages of Data Driven testing:

Some Drawbacks of Data Driven Automation Testing method are:

  1. Quality of the test is depended on the automation skills of the Implementing team
  2. Data validation is a time-consuming task when testing large amount of data.
  3. Maintenance is a big issue as large amount of coding needed for Data-Driven testing.
  4. High-level technical skills are required. A tester may have to learn an entirely new scripting language.
  5. There will be more documentation. Mostly related to scripts management tests infrastructure and testing results.
  6. A text editor like Notepad is required to create and maintain data files.

Conclusion:

  • Data-driven is a test automation framework which stores test data in a table or spread spreadsheet format.
  • In Data-driven test automation framework, input data can be stored in single or multiple data sources like xls, XML, csv, and databases.
  • To create an individual test for each data set is a lengthy and time-consuming process. Data Driven Testing framework resolves this issue by keeping the data separate from Functional tests.
  • In Data Driven Testing, it is an ideal option to use realistic information
  • It allows testing application with multiple sets of data values during Regression testing
  • Drawback of this method is that it is depended on the automation skills of the Implementing team

I have a BDD-style test case in my robot framework. Which is calling the API. There is a variable in API, which value changes. So I want to write only one test case and want that variable to be changed after one has executed.

Please find the code below:


*** Variables *** ${Upload_Project_Asset_To_Flagship_API} /workstream/api/projects/${projectId}/assets/${assetId}/external?debug=1&user_id=${userId} *** Test Cases *** TC_01: When User Executes Upload Asset To Flagship API Then Assert the response after asset upload [Teardown] User gets the uploaded file details *** Keywords *** User Executes Upload Asset To Flagship API ${resp}= Put request session1 ${Upload_Project_Asset_To_Flagship_API} headers=${api_header}

  • Selenium Tutorial
  • Selenium – Home
  • Selenium – Overview
  • Selenium – Environment Setup
  • Selenium – Remote Control
  • Selenium – IntelliJ
  • Selenium IDE Tutorial
  • Selenium IDE – Introduction
  • Selenium IDE – Features
  • Selenium IDE – Creating Tests
  • Selenium IDE – Selenese Commands
  • Selenium IDE – Actions Commands
  • Selenium IDE – Accessors Commands
  • Selenium IDE – Assertions Commands
  • Selenium IDE – Script Debugging
  • Selenium IDE – Verification Points
  • Selenium IDE – Pattern Matching
  • Selenium IDE – Browser Execution
  • Selenium IDE – User Extensions
  • Selenium WebDriver Tutorial
  • Selenium WebDriver – Overview
  • Selenium WebDriver – Installation
  • Selenium WebDriver – First Test Script
  • Selenium WebDriver – Chrome Options
  • Selenium WebDriver Web Elements
  • Selenium Webdriver – Find All Links
  • Selenium WebDriver – User Interactions
  • Selenium WebDriver – WebElement Commands
  • Selenium WebDriver – Browser Interactions
  • Selenium WebDriver – Browser Navigation
  • Selenium WebDriver – Handling Forms
  • Selenium WebDriver – Windows and Tabs
  • Selenium WebDriver – Handling Links
  • Selenium WebDriver – Input Boxes
  • Selenium WebDriver – Radio Button
  • Selenium WebDriver – Checkboxes
  • Selenium WebDriver – Dropdown Box
  • Selenium WebDriver – Handling Cookies
  • Selenium WebDriver – Dynamic Web Tables
  • Selenium WebDriver – Actions Class
  • Selenium WebDriver – Action Class
  • Selenium Webdriver – Keyboard Events
  • Selenium Webdriver – Key Up/Down
  • Selenium Webdriver – Copy and Paste
  • Selenium Webdriver – Mouse Events
  • Selenium Webdriver – Drag and Drop
  • Selenium Webdriver – Scroll Operations
  • Selenium WebDriver – Waiting Strategies
  • Selenium – Explicit/Implicit Wait
  • Selenium WebDriver – Support Features
  • Selenium Webdriver – Multi Select
  • Selenium Webdriver – Wait Support
  • Selenium Webdriver – Select Support
  • Selenium Webdriver – Color Support
  • Selenium WebDriver – Errors & Logging
  • Selenium Webdriver – Logging
  • Selenium Webdriver – Exception Handling
  • Selenium WebDriver – Miscellaneous
  • Selenium Webdriver – Multi Windows Testing
  • Selenium Webdriver – JavaScript Executor
  • Selenium Webdriver – Headless Execution
  • Selenium Webdriver – Capture Screenshots
  • Selenium Webdriver – Capture Videos
  • Selenium WebDriver – Page Object Model
  • Selenium Grid Tutorial
  • Selenium Grid – Overview
  • Selenium Reporting Tools
  • Selenium – TestNG
  • Selenium & other Technologies
  • Selenium – Java Tutorial
  • Selenium – Python Tutorial
  • Selenium – C# Tutorial
  • Selenium – Javascript Tutorial
  • Selenium – Kotlin Tutorial
  • Selenium – Ruby Tutorial
  • Selenium – Maven & Jenkins
  • Selenium – Database Testing
  • Selenium – LogExpert Logging
  • Selenium – Log4j Logging
  • Selenium – Robot API
  • Selenium – AutoIT
  • Selenium – Flash Testing
  • Selenium – Apache Ant
  • Selenium – Github
  • Selenium – SoapUI
  • Selenium – Cucumber
  • Selenium – IntelliJ
  • Selenium – XPath
  • Selenium Miscellaneous Concepts
  • Selenium – Alternatives
  • Selenium Useful Resources
  • Selenium – Quick Guide
  • Selenium – Useful Resources
  • Selenium – Automation Practice
  • Selenium – Discussion

Selenium – Data Driven using Excel

While designing a test, parameterizing the tests is inevitable. We will make use of Apache POI – Excel JAR’s to achieve the same. It helps us read and write into Excel.

Part 18-  Data Driven Testing Using Script in Robot Framework | Selenium with Python
Part 18- Data Driven Testing Using Script in Robot Framework | Selenium with Python

Keywords searched by users: data driven in selenium

Selenium Data Driven Framework Using Java | Data Driven Testing Framework  In Selenium - Youtube
Selenium Data Driven Framework Using Java | Data Driven Testing Framework In Selenium – Youtube
What Is Data Driven Testing? Learn To Create Framework
What Is Data Driven Testing? Learn To Create Framework
Data Driven Framework In Selenium Webdriver | Software Testing Material
Data Driven Framework In Selenium Webdriver | Software Testing Material
Selenium Framework: Data, Keyword & Hybrid Driven
Selenium Framework: Data, Keyword & Hybrid Driven
Data Driven Framework In Selenium Webdriver | Data Driven Testing | Selenium  | Edureka Rewind - Youtube
Data Driven Framework In Selenium Webdriver | Data Driven Testing | Selenium | Edureka Rewind – Youtube
Data Driven Vs Keyword Driven Frameworks For Test Automation
Data Driven Vs Keyword Driven Frameworks For Test Automation
Selenium Framework Tutorial | Data Driven Framework - Scientech Easy
Selenium Framework Tutorial | Data Driven Framework – Scientech Easy
Data Driven Framework In Selenium With Apache Poi, Xssfworkbook
Data Driven Framework In Selenium With Apache Poi, Xssfworkbook
Selenium Framework: Data, Keyword & Hybrid Driven
Selenium Framework: Data, Keyword & Hybrid Driven
Data Driven Framework In Selenium Webdriver Part 1 - Youtube
Data Driven Framework In Selenium Webdriver Part 1 – Youtube
Selenium Framework: Data, Keyword & Hybrid Driven
Selenium Framework: Data, Keyword & Hybrid Driven
Kiểm Thử Theo Hướng Data-Driven Với Selenium Ide | Topdev
Kiểm Thử Theo Hướng Data-Driven Với Selenium Ide | Topdev

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *