DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Apex Testing: Tips for Writing Robust Salesforce Test Methods
  • Solid Testing Strategies for Salesforce Releases
  • A General Overview of TCPCopy Architecture
  • Modes and Modality in Performance Testing

Trending

  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Scalable System Design: Core Concepts for Building Reliable Software
  • Accelerating AI Inference With TensorRT
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How To Use DataProviders In TestNG [With Examples]

How To Use DataProviders In TestNG [With Examples]

DataProvider in TestNG is used to inject multiple values into the same test case, this guide explains how to use them in your Selenium test automation scripts.

By 
Kritika Murari user avatar
Kritika Murari
·
Oct. 05, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
14.0K Views

Join the DZone community and get the full member experience.

Join For Free

Parameterization In TestNG helps us pass data through the code and prevent hard-coding. However, TestNG parameters enable us to pass the values only once per execution cycle. To overcome this, we can use DataProvider in TestNG that allows us to pass multiple parameters to a single test in a single execution. Using DataProviders, we can easily pass multiple values to a test in just one execution cycle.

Let us quickly jump onto understanding more about DataProvider in TestNG and how we can efficiently use them in our test scripts for Selenium test automation.

What Is a DataProvider in TestNG?

Similar to TestNG Parameters, DataProviders are a means to pass data to test scripts in TestNG. Using DataProvider in TestNG, we can easily inject multiple values into the same test case. It comes inbuilt in TestNG and is popularly used in data-driven frameworks.

The syntax for a DataProvider in TestNG is as follows:

Java
xxxxxxxxxx
1
 
1
@DataProvider(name = ”name of the data provider”)
2
public Object[][] dataProviderfunc(){
3
Return new Object[][]{
4
values
5
}
6
}


Now, let’s try to understand the different components of this syntax.

  • The DataProvider annotation has a single attribute called name, which you can select as per your convenience.

  • DataProviders are separate methods used in test functions, which means that this annotation is not used on test functions like the testNG parameters.

  • The DataProvider method returns a 2D list of objects.

  • In case you do not define a name for the DataProvider, the DataProvider method name is considered its default name. So, the name of the DataProvider calls the DataProvider method.

TestNG Annotations provide additional information about the class or method we defined above. It is usually represented by the ‘@’ prefix. TestNG uses these annotations to help in making a robust framework.

Using DataProvider in TestNG

Now that you understand the basics of DataProviders, it is time to know how to use DataProvider in TestNG. DataProviders are most useful when you need to pass complex TestNG parameters. Shown below is a basic example of using the DataProvider in TestNG script.

Java
xxxxxxxxxx
1
51
 
1
 package dataProviders;
2
import org.openqa.selenium.By;
3
import org.openqa.selenium.Keys;
4
import org.openqa.selenium.WebDriver;
5
import org.openqa.selenium.WebElement;
6
import org.openqa.selenium.chrome.ChromeDriver;
7
import org.testng.Reporter;
8
import org.testng.annotations.AfterMethod;
9
import org.testng.annotations.BeforeMethod;
10
import org.testng.annotations.DataProvider;
11
import org.testng.annotations.Test;
12
 
13
public class SimpleTest {
14
    
15
    WebDriver driver;
16
    
17
    @DataProvider(name = "test-data")
18
    public Object[][] dataProvFunc(){
19
        return new Object[][]{
20
                {"Lambda Test"},{"Automation"}
21
        };
22
    }
23
    
24
    @BeforeMethod
25
      public void setUp() {
26
        
27
          System.out.println("Start test");
28
          System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
29
          driver = new ChromeDriver();
30
          String url = "https://www.google.com";
31
          driver.get(url);
32
          driver.manage().window().maximize();
33
        
34
      }
35
    //Passing the dataProvider to the test method through @Test annotation
36
    @Test(dataProvider ="test-data")
37
    public void search(String keyWord){
38
        WebElement txtBox = driver.findElement(By.xpath("//input[@class='gLFyf gsfi']"));
39
          txtBox.sendKeys(keyWord);
40
          Reporter.log("Keyword entered is : " +keyWord);
41
          txtBox.sendKeys(Keys.ENTER);
42
          Reporter.log("Search results are displayed.");
43
    }
44
    
45
    @AfterMethod
46
    public void burnDown(){
47
        driver.quit();
48
    }
49
 
50
}


In the code above, I am passing two search keywords, viz “Lambda Test” and “Automation” to my test method using the DataProvider method. You can run the code and check the output. It will be as shown below-

Starting test

test file structure

Did you notice two values being passed to the search method while we ran the test just once?

That is the beauty of DataProvider! Another great thing about using TestNG are the interfaces known as listeners. TestNG listeners are modules that listen to certain events and keep track of test execution while performing some action at every stage of test execution.

Now, let us try to clean up our code and inherit this DataProvider from another class. This is important because keeping everything in one place might become messy. Inheritance would come to our rescue then, let us see how in the next section.

Inheriting DataProvider in TestNG

As mentioned above, DataProvider in TestNG plays an essential role in writing codes for complex projects or objects. While writing test cases, the code tends to get very messy. It is always preferred to declare the test case in one class and define TestNG parameters like DataProviders in another class. In other words, we are inheriting DataProvider from another file, and that is what inheriting a DataProvider in TestNG is all about. Let us create separate classes for the DataProvider method and the test method, as shown below:

DataProvider Class

Java
xxxxxxxxxx
1
11
 
1
package dataProviders;
2
import org.testng.annotations.DataProvider;
3
public class DPClass {
4
    @DataProvider(name = "test-data")
5
    public static Object[][] dataProvFunc(){
6
            return new Object[][]{
7
                {"Lambda Test"},{"Automation"}
8
            };
9
    }
10
}
11


We can see that all we did was mark the DataProvider method as static and create a new class.

Test Class-

Java
xxxxxxxxxx
1
38
 
1
package dataProviders;
2
import org.openqa.selenium.By;
3
import org.openqa.selenium.Keys;
4
import org.openqa.selenium.WebDriver;
5
import org.openqa.selenium.WebElement;
6
import org.openqa.selenium.chrome.ChromeDriver;
7
import org.testng.Reporter;
8
import org.testng.annotations.AfterMethod;
9
import org.testng.annotations.BeforeMethod;
10
import org.testng.annotations.Test;
11
 
12
public class TestClass {
13
WebDriver driver;
14
    
15
    @BeforeMethod
16
      public void setUp() {
17
              System.out.println("Start test");
18
              System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
19
              driver = new ChromeDriver();
20
              String url = "https://www.google.com";
21
              driver.get(url);
22
              driver.manage().window().maximize();
23
          }
24
    
25
    @Test(dataProvider ="test-data", dataProviderClass=DPClass.class)
26
    public void search(String keyWord){
27
            WebElement txtBox = driver.findElement(By.xpath("//input[@class='gLFyf gsfi']"));
28
              txtBox.sendKeys(keyWord);
29
              Reporter.log("Keyword entered is : " +keyWord);
30
              txtBox.sendKeys(Keys.ENTER);
31
              Reporter.log("Search results are displayed.");
32
    }
33
    
34
    @AfterMethod
35
    public void burnDown(){
36
            driver.quit();
37
    }
38
}


As you can see, to handle the inheritance, all we did was add an attribute to the test method (highlighted above), which specifies the class that has the DataProvider method. On running the above test, you will see the results similar to what we saw in our first execution.

output after the first execution

Next, we will see passing multiple values for a single TestNG parameter using DataProvider in TestNG.

Passing Multiple Parameter Values in TestNG DataProviders

Passing multiple values is pretty similar to passing numerous parameters. The only difference is that we will pass various values to a single parameter so that a string of input(s) is sent in one go. Let us quickly understand it with the help of the code.

Java
xxxxxxxxxx
1
42
 
1
package dataProviders;
2
import org.openqa.selenium.By;
3
import org.openqa.selenium.Keys;
4
import org.openqa.selenium.WebDriver;
5
import org.openqa.selenium.WebElement;
6
import org.openqa.selenium.chrome.ChromeDriver;
7
import org.testng.Reporter;
8
import org.testng.annotations.AfterMethod;
9
import org.testng.annotations.BeforeMethod;
10
import org.testng.annotations.DataProvider;
11
import org.testng.annotations.Test;
12
public class SimpleTest {
13
    WebDriver driver;
14
    @DataProvider(name = "test-data")
15
    public Object[][] dataProvFunc(){
16
            return new Object[][]{
17
                {"Selenium","Delhi"},{"QTP","Bangalore"},{"LoadRunner","Chennai"}
18
            };
19
    }
20
    @BeforeMethod
21
      public void setUp() {
22
              System.out.println("Start test");
23
              System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
24
              driver = new ChromeDriver();
25
              String url = "https://www.google.com";
26
              driver.get(url);
27
              driver.manage().window().maximize();
28
             
29
      }
30
    @Test(dataProvider ="test-data")
31
    public void search(String keyWord1, String keyWord2){
32
            WebElement txtBox = driver.findElement(By.xpath("//input[@class='gLFyf gsfi']"));
33
              txtBox.sendKeys(keyWord1," ",keyWord2);
34
              Reporter.log("Keyword entered is : " +keyWord1+ " " +keyWord2);
35
              txtBox.sendKeys(Keys.ENTER);
36
              Reporter.log("Search results are displayed.");
37
    }
38
    @AfterMethod
39
    public void burnDown(){
40
            driver.quit();
41
    }
42
}


Run the test script, and you will see both the values for the TestNG parameters being passed in one go, the output for it would be as follows:

results of running test class

You might not know, but this is not the only way to read data in DataProviders. You can use external files to read the data and pass on to the test script through the DataProviders; one such external file is an Excel File. Next, we will see how to use an Excel file to fetch data and subsequently pass on to the DataProvider method. Without wasting any more time, let us walk through how this can be done.

DataProvider In TestNG Using Excel

Using Excel for DataProvider in TestNG is one of the most convenient ways to read the data. By doing so, our job becomes extremely easy when dealing with vast amounts of data. To do so, we need to follow some simple steps in order to achieve our target of using Excel as a DataProvider.

Create a Test Data Sheet

Simply create a new package under your project directory and keep the external files under the same project. I have named my package as “testData” under which I am saving my data excel file “TestData.xlsx.” So, my data sheet looks like below:

data set in excel

Next, we will create a DataProvider method that will use another method to read the excel file & create a 2D object from the row & column values of the excel and return the same value, so that our test script can use it. The code for it would look like below-

Java
xxxxxxxxxx
1
33
 
1
@DataProvider(name ="excel-data")
2
    public Object[][] excelDP() throws IOException{
3
            //We are creating an object from the excel sheet data by calling a method that reads data from the excel stored locally in our system
4
            Object[][] arrObj = getExcelData("Location of the excel file in your local system","Name of the excel sheet where your data is placed");
5
            return arrObj;
6
    }
7
    //This method handles the excel - opens it and reads the data from the respective cells using a for-loop & returns it in the form of a string array
8
    public String[][] getExcelData(String fileName, String sheetName){
9
            
10
            String[][] data = null;     
11
        try
12
        {
13
        FileInputStream fis = new FileInputStream(fileName);
14
        XSSFWorkbook wb = new XSSFWorkbook(fis);
15
        XSSFSheet sh = wb.getSheet(sheetName);
16
        XSSFRow row = sh.getRow(0);
17
        int noOfRows = sh.getPhysicalNumberOfRows();
18
        int noOfCols = row.getLastCellNum();
19
        Cell cell;
20
        data = new String[noOfRows-1][noOfCols];
21
        for(int i =1; i<noOfRows;i++){
22
             for(int j=0;j<noOfCols;j++){
23
                   row = sh.getRow(i);
24
                   cell= row.getCell(j);
25
                   data[i-1][j] = cell.getStringCellValue();
26
               }
27
        }
28
        }
29
        catch (Exception e) {
30
               System.out.println("The exception is: " +e.getMessage());
31
                        }
32
            return data;
33
    }


After doing so, we can simply pass the Data Provider in TestNG to our test method and our final code would look like below: 

Java
x
79
 
1
package testNG;
2
import java.io.FileInputStream;
3
import java.io.IOException;
4
import org.apache.poi.ss.usermodel.Cell;
5
import org.apache.poi.xssf.usermodel.XSSFRow;
6
import org.apache.poi.xssf.usermodel.XSSFSheet;
7
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
8
import org.openqa.selenium.By;
9
import org.openqa.selenium.Keys;
10
import org.openqa.selenium.WebDriver;
11
import org.openqa.selenium.WebElement;
12
import org.openqa.selenium.chrome.ChromeDriver;
13
import org.testng.Reporter;
14
import org.testng.annotations.AfterMethod;
15
import org.testng.annotations.BeforeMethod;
16
import org.testng.annotations.DataProvider;
17
import org.testng.annotations.Test;
18
public class ExcelDataProvider {
19
 
20
    WebDriver driver;
21
    @BeforeMethod
22
      public void setUp() {
23
              System.out.println("Start test");
24
              System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
25
              driver = new ChromeDriver();
26
              String url = "https://www.google.com";
27
              driver.get(url);
28
              driver.manage().window().maximize();
29
             
30
      }
31
    
32
    @DataProvider(name ="excel-data")
33
    public Object[][] excelDP() throws IOException{
34
            //We are creating an object from the excel sheet data by calling a method that reads data from the excel stored locally in our system
35
            Object[][] arrObj = getExcelData("Location of the excel file in your local system","Name
36
of the excel sheet where your data is placed");
37
            return arrObj;
38
    }
39
    //This method handles the excel - opens it and reads the data from the respective cells using a for-loop & returns it in the form of a string array
40
    public String[][] getExcelData(String fileName, String sheetName){
41
            
42
            String[][] data = null;     
43
        try
44
        {
45
        FileInputStream fis = new FileInputStream(fileName);
46
        XSSFWorkbook wb = new XSSFWorkbook(fis);
47
        XSSFSheet sh = wb.getSheet(sheetName);
48
        XSSFRow row = sh.getRow(0);
49
        int noOfRows = sh.getPhysicalNumberOfRows();
50
        int noOfCols = row.getLastCellNum();
51
        Cell cell;
52
        data = new String[noOfRows-1][noOfCols];
53
        
54
        for(int i =1; i<noOfRows;i++){
55
             for(int j=0;j<noOfCols;j++){
56
                   row = sh.getRow(i);
57
                   cell= row.getCell(j);
58
                   data[i-1][j] = cell.getStringCellValue();
59
               }
60
        }
61
        }
62
        catch (Exception e) {
63
               System.out.println("The exception is: " +e.getMessage());
64
            }
65
            return data;
66
    }
67
    @Test(dataProvider ="excel-data")
68
    public void search(String keyWord1, String keyWord2){
69
            WebElement txtBox = driver.findElement(By.xpath("//input[@class='gLFyf gsfi']"));
70
              txtBox.sendKeys(keyWord1," ",keyWord2);
71
              Reporter.log("Keyword entered is : " +keyWord1+ " " +keyWord2);
72
              txtBox.sendKeys(Keys.ENTER);
73
              Reporter.log("Search results are displayed.");
74
    }
75
    @AfterMethod
76
    public void burnDown(){
77
            driver.quit();
78
    }   
79
}


Now on running this code you will see results like below:

final result

Conclusion

In this tutorial, we saw how easily TestNG parameters or utilities, like the DataProviders, enable us to execute our test scripts. When we might have n-number of data combinations to test, DataProvider in TestNG can be used without the hassle of hard-coding any test value in the scripts. This TestNG parameter is especially useful when you want to integrate your external data files like an Excel file into the same code. 

That is how DataProvider in TestNG plays a vital role in Selenium test automation scripts. I recommend you to run all the above codes and check the output. We must also note that a DataProvider in TestNG returns a 2-D array, unlike other TestNG parameters. We can leverage these TestNG parameters to make the best of existing Selenium test automation scripts or create new scripts. 

Happy testing!

TestNG Test data Pass (software) Test method

Published at DZone with permission of Kritika Murari. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Apex Testing: Tips for Writing Robust Salesforce Test Methods
  • Solid Testing Strategies for Salesforce Releases
  • A General Overview of TCPCopy Architecture
  • Modes and Modality in Performance Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!