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.

Learn more on Apache POI

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.

1
2
3
4
5
6
7
8
9
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
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.

1
2
3
4
5
6
7
8
9
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
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.

1
2
3
4
5
6
7
8
9
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
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