What is Selenium Framework?


Selenium framework is a code structure that is used to make code maintenance simpler and readability better. It helps in dividing the entire code into smaller parts of the code in a systematic way, which test a particular functionality.

Without a framework at starting, we had written complete code and data in the same place that was neither reusable nor readable. But using selenium framework, we can create the structure of code in better ways.

We can keep "test data" separate from the actual test cases which help to analyze and update data easy. It increases code readability, helps to get the desired results in a systematic way and reduces script maintenance cost.

Why do we need a Selenium Framework?


1. Without a framework, a single test case may have a million lines of code and it will test the entire functionality of the application. Now, suppose you need to modify any particular functionality later time so is it possible to read the entire code again for a particular functionality? 

Hope that your answer will be No because reading so huge test case will be tough and boring and you also need lots of time to analyze the entire code. But when we use selenium framework structure, it breaks the entire code into small parts. These smaller parts can be easily readable if we need to modifying and can perform a particular function.

2. Using selenium framework structure, we can easily find and fix bugs or defects in a million lines of code in a short time. 
3. Selenium framework is easy to use and also provides flexibility in our code.
4. It makes our code simple, understandable, and readable. 
For these reasons, we need to use selenium framework.

Advantages of Selenium Framework Design


There are several advantages to using a selenium automation framework. They are as follows:
1. Increases code reusability.
2. Easier to use.
3. Improved code understandability and readability.
4. The automation framework provides flexibility to code.
5. Reduces script maintenance.

Disadvantages of Selenium Framework


Using an automation framework can have several disadvantages. They are as follows:
1. It consumes more time to develop.
2. Slower to execute.
3. More complex to create and debug.

Types of Framework Designing in Selenium


There are several types of automation testing framework available to use in selenium, but the three most commonly used selenium framework designed are shown in the below figure.
Different types of Selenium Framework
1. Data-Driven Framework: 
2. Keyword Driven Framework 
3. Hybrid Framework 

When to Design Data Driven, Keyword Driven, and Hybrid Frameworks in Selenium?


1. Data Driven Framework: Data-driven framework is designed to work with those applications where we want to test multiple sets of data than multiple functionalities of the application. i.e. In data-driven framework, importance is given to Test Data in comparison to multiple functionalities of the application. For example, data-driven framework is generally designed to test login web page by different sets of Test Data. 

2. Keyword Driven Framework: Keyword-driven framework is designed to work with those applications where we want to test multiple functionalities of the application than Test Data. i.e. In the keyword-driven framework, importance is given to multiple functionalities of the application in comparison to Test Data.

For example, suppose we have a railway reservation application which provides many features such as
1. Login to application by entering credentials.
2. Search Trains.
3. Book Train tickets
4. Cancel tickets.
5. Train offers.
6. PNR status
7. View reports and so on.
To test these kinds of functionality in the application, we can test easily by designing keyword driven automation framework.

3. Hybrid Framework: This framework is a combination of data driven and keyword driven frameworks. Hybrid framework is designed for those applications where we want to test multiple functionalities of application with different sets of Test Data. i.e in hybrid framework, importance is given for Test Data and multiple functionalities of application.

After proper analyzing of the application, you can decide what kind of framework is best suited for your needs and then you can easily design and structure of automation framework in selenium. 
In this tutorial, we will learn the data-driven automation framework which is one of the most popular Automation Testing Framework in the current market.

Data-Driven Framework in Selenium


A DataDriven Framework in selenium is a technique in which we keep input test data separate from the actual test script (code). This framework is completely dependent on the input test data. There are two components in the data driven framework. First is test script and second test data.

The test data set is created in the external sources such as an excel file, CSV file, XML or any database table and we then connect test script with test data to get multiple sets of data to perform the software under test. Take a look at the following block diagram of data driven framework. 
Data driven framework block diagram
In the data-driven framework, we store test data and expected output data/results in a separate data file so that a single script can execute all the test cases with multiple sets of data.

Why do we need Data-Driven Framework in Selenium?


Let's understand it with an example scenario. Assume that we need to test the login/Register to a webpage with 100 different data sets of username and password.
To test this login webpage, we have three different approaches:

1) Create 100 scripts, one for each data set and execute each test one by one.
2) Change the data in the script every time and execute it multiple times.
3) Place all our test data in excel sheets, connect with test script and execute the script multiple times with different data.

First two scenarios are laborious, time-consuming and of course boring. Hence, we should go towards the third approach in which we will implement the Data Driven framework technique, where the multiple sets of username and password will be placed credentials in an excel sheet and passed the credentials to the code ( Java class file) to perform automation on the browser.

In addition, we can also easily control how much data needs to be tested. If necessary, we can easily increase the number of test parameters by adding more username and password fields to the excel file (or other sources).

Since we place the test data separate from test case. Therefore, we can easily modify the test case for a particular functionality without changing other portion of code. For example, suppose we want to modify the code for login functionality, we can modify related code just instead of modifying any other dependent portion in the same code.

Hope that you will have understood the need and importance of Data-driven framework in selenium. 
Key point:
In simple words, we need to implement a Data-Driven Framework when we have to execute the same test script with different sets of test data.

How to Design Data-Driven Framework in Selenium using Apache POI?


Selenium WebDriver is a popular tool to automate web-based applications but it has also some limitations. It does not directly support read and write operations on excel file. Therefore, we will use third-party APIs like Apache POI for reading/ writing to any Microsoft Office document.

You can learn Apache POI step-by-step from the below link.
👉 Apache POI Tutorial | Download & Installation JAR files
Download the Apache POI API ( set of JAR files) and place them along with the set of Selenium JARs.

Let's create an automation script to test the login functionality of a web-based application. Here, I have taken Linkedin application as an example. Look at a glance at the following test scenario. Here, we are executing two test cases.
Test Case 1:
1. Launch the Firefox browser.
2. Open Linkedin login page "https://www.linkedin.com/login".
3. Enter your credential email and password to go to Linkedin home page.
4. Click on Sign in button.
5. And then sign out from the home page.
Test Case 2:
1. Click on Sign in button on Linkedin page.
2. Again Enter your email and password to be redirected on Linkedin home page.
3. Click on the Sign-in button.
4. And then sign out from the home page.

Now, you will need the following software installed on your system to execute the framework.
1. Java JDK 1.7+
2. Eclipse IDE
3. Selenium jars
4. Apache POI Jars
5. Microsoft Office

Steps to create Data-Driven Framework in Selenium using Apache POI 

The structure of the project (Data-Driven Project) is shown in the below screenshot.

Data driven folder structure

Step 1: First open Eclipse and configure Apache POI jar files – Download Apache Jars. Now unzip the jar file, and add the following jars into your project and configure them.

Step 2: Open Excel Sheet and enter some test data (username & password) as shown in the below screenshot. Now save it as "ExcelData.xlsx" at your preferred location. I have saved my excel sheet in C drive.

Excel sheet in data driven framework

Step 3: Create a java project named "Data Driven Framework using POI" in your Eclipse IDE. An src folder will be made that is still empty. The src folder stands for source files that contain all the test scripts, generics, readers, and utilities.

If you expand src folder, you will see a hierarchy of package folder that group our source files. All these source files are simple java classes.

Step 4: Create a package named "testData" and place saved "ExcelSheet.xlsx"  file inside this package directory locally on your computer. Go to scr folder > testData. Now, refresh your project folder in Eclipse.

Step 5: Create a package named "utility" in which we will create a java class file named "Constant" where we will declare all constants such as URL, filePath, and testData. Let's see the following source code to define all constants used in this project.
Constants code:
    package utility; public class Constant { public static final String URL = "https://www.linkedin.com/login"; public static final String filePath = "C:\\selenium_wrkspce\\Data-Driven Framework Using POI\\src\\testData\\ExcelSheet.xlsx"; public static final String testData = "ExcelSheet.xlsx"; }
Step 6: Create a package named "excelUtility" that will contain two java class files such as ReadExcelSheet and WriteExcelResult. ReadExcelSheet class has been created to read data from the excel sheet. WriteExcelResult class has been created to write result on excel sheet after the execution of test script.

ReadExcelSheet code:
    package excelUtility; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import utility.Constant; public class ReadExcelSheet { public ArrayList readExcelData(int colNo) throws IOException { // Call filePath variable using class name. String filePath = Constant.filePath; // Create an object of file class and pass filePath as an input parameter to its constructor. File file = new File(filePath); // Create an object of FileInputStream class and pass file as parameter to its constructor. FileInputStream fis = new FileInputStream(file); // Create an object of XSSFWorkbook class and pass fis as parameter to its. XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheet("Sheet1"); Iterator<Row> row = sheet.rowIterator(); row.next(); // Create an ArrayList object of String type. It will accept String value only. ArrayList<String> ar = new ArrayList<String>(); // Checking the next element availability using reference variable row. while(row.hasNext()) { // Moving cursor to next Row using reference variable row. Row r = row.next(); // Moving cursor to the cell by getting cell number. Cell c = r.getCell(colNo); // Read the value of the cell using getStringCellValue() method. String data = c.getStringCellValue(); // Adding the value of the cells in the Arraylist by passing 'data'. ar.add(data); // OR One line code: ar.add(row.next().getCell(colNo).getStringCellValue()); } System.out.println("List: " +ar); // Return the data to readExcelData() method of type ArrayList. return ar; } }
WriteExcelResult code:
    package excelUtility; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import utility.Constant; public class WriteExcelResult { static XSSFRow row; static XSSFCell cell; public static void setCellData(String Result, int RowNum, int ColNum) throws Exception { File file = new File(Constant.filePath); FileInputStream fis = new FileInputStream(file); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheet("Sheet1"); sheet.getRow(RowNum).createCell(ColNum).setCellValue(Result); FileOutputStream fos = new FileOutputStream(Constant.filePath); wb.write(fos); fos.flush(); fos.close(); System.out.println("Result: Passed"); } }
👉 Reading Excel File in Java using POI API
👉 How to write Excel File in Java using Apache POI

Step 7: Create a package named "loginData" where we will create a class "LoginTest". Let's understand the following source code step by step.
LoginTest code:
    package loginData; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import excelUtility.ReadExcelSheet; import utility.Constant; public class LoginTest { public void loginSetUp() throws IOException { // Create an WebDriver object to launch Firefox browser. WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); // Declaration of variable URL with datatype String and store the URL of the web page. String url = Constant.URL; // Call get() command and pass url as a parameter. driver.get(url); // Wait for Page to load completely. driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); // Create an object of ReadExcelSheet class. ReadExcelSheet rs = new ReadExcelSheet(); // Call readExcelData() method by passing column number 1 and 2 using reference variable rs. // Since the return type of this method is ArrayList of String, we will store them by using variables userName and passWord of type ArrayList. ArrayList userName = rs.readExcelData(1); ArrayList passWord = rs.readExcelData(2); for(int i=0; i < userName.size(); i++) { // Locate web element username by By.xpath. WebElement username = driver.findElement(By.xpath("//input[@id = 'username']")); String str1 = userName.get(i); // Get the username from the excel sheet one by one. // Call sendKeys() method to send username. username.sendKeys(str1); // Or One line code: username.sendKeys(userName.get(i)); // Locate web element password by By.xpath. WebElement password = driver.findElement(By.xpath("//input[@id='password']")); password.sendKeys(passWord.get(i)); WebElement signIn = driver.findElement(By.xpath("//button[text() = 'Sign in']")); signIn.click(); WebElement profile = driver.findElement(By.xpath("//img[@id = 'ember26']")); profile.click(); driver.findElement(By.xpath("//a[text() = 'Sign out']")).click(); driver.findElement(By.xpath("//a[text() = 'Sign in']")).click(); } System.out.println("Test is successful"); driver.close(); } }
Step 8: Create a package named "execution". Inside this package, create a class named it "ExecuteTestcase". See the below source code.
ExecuteTestcase code:
    package execution; import excelUtility.WriteExcelResult; import loginData.LoginTest; public class ExecuteTestcase { public static void main(String[] args) throws Exception { // Create an object of LoginTest class. LoginTest t = new LoginTest(); t.loginSetUp(); // Calling loginSetUp method. WriteExcelResult.setCellData("Pass", 1, 3); WriteExcelResult.setCellData("Pass", 2, 3); } }
On executing "ExecuteTestcase" class, we will get the following output.
    Output: List: [xyz@gmail.com, xyz@yahoo.com] List: [deep986, deep986#] Test is successful. Result: Passed Result: Passed
Now, it's time to see test result on excel sheet. The result is shown in the below screenshot. The result is pass for both tests.
Excel sheet after data driven testing

Advantages of Data-Driven Framework in Selenium


1. Data-driven framework helps to reduce the repetition of the same task again and again.
2. It reduces the number of test scripts needed to implement all test cases.
3. It requires less amount of code to generate all test cases.
4. The test data is created before test implementation.
5. It is secure and easy to maintain.

Final words
Hope that this tutorial has covered almost all important points related to Selenium framework and Data-driven framework with scenario. I hope that you will have understood this data-driven framework and enjoyed it.