Parametrization in Selenium: DataProvider and TestNG XML
Parameterization in Selenium is a technique used to run the same test with multiple data sets. It enhances test coverage and efficiency by allowing data-driven testing, where input values are read from external sources like Excel, CSV files, or databases, automating scenarios with various data inputs.
When we develop our software, we always want our application to work with different data sets. And we expect the same thing when we test that software and application. Hence, we need to verify that our system is taking all combinations expected to support. In the Automation testing with Selenium, Parameterization is crucial in enhancing test coverage, reducing redundancy, and improving maintainability. DataProvider and TestNG XML are powerful features that facilitate seamless Parameterization, enabling testers to execute the same test case with different data sets effortlessly. This article explores how we can use DataProvider and TestNG XML for Parameterization in Selenium, empowering testers to write efficient and scalable automation scripts.
Table of Contents
- What is Parameterization in Selenium?
- Using Parameters annotation and TestNG XML file
- Using DataProviderannotation
- Best Practices for Parameterization
What is Parameterization in Selenium?
Parameterization in Selenium refers to the process of dynamically passing parameters or input data to test methods or test scripts. This allows testers to execute the same test logic with different data sets, thereby enhancing test coverage, reducing redundancy, and improving maintainability. Parameterization is a fundamental concept in data-driven testing, where test scenarios are executed with various input values to validate application functionality across different scenarios.
In Selenium, Parameterization can be achieved using various techniques, including:
1. TestNG DataProviders:
TestNG, a popular Java testing framework, provides a feature called DataProviders. Test methods annotated with @Test can receive parameters from DataProviders, allowing testers to supply test data from external sources such as arrays, Excel sheets, databases, or custom data sources.
2. Parameterization using TestNG XML
TestNG XML allows testers to configure test suites, test cases, and parameters for test execution. TestNG XML files can specify parameters that are passed to test methods during execution, enabling testers to customize test behavior without modifying the test code.
3. Excel or CSV Files
Test data can be stored in Excel spreadsheets or CSV files, and Selenium scripts can be written to read data from these external files dynamically. This approach decouples test data from test scripts, making it easier to manage and update test data independently.
4. Properties Files
Test parameters can be stored in properties files, and Selenium scripts can read these properties files to retrieve test data or configuration values. This allows testers to centralize configuration settings and share them across multiple tests or test suites.
5. Command-line Arguments
Selenium scripts can accept command-line arguments, which can be used to pass parameters or configuration values during test execution. This approach provides flexibility in specifying test configurations without modifying the test code.
In this article we will discuss two ways by which we can achieve parameterization in TestNG.
- Using Parameters annotation and TestNG XML file.
- Using DataProvider annotation.
Before discussing the above two ways by writing code in Java, create a maven project in Eclipse/Intellij IDE or any other as per your requirement.
Best-suited Selenium courses for you
Learn Selenium with these high-rated online courses
Using Parameters Annotation and TestNG XML file
Create any java class; the Parameterization.java class is created in the code below. In this class, we have created three test case methods: add, subtract and multiply for addition, subtraction and multiplication of numbers passed using TestNG annotation @parameters.
In pom.xml file include the below dependencies:
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --><dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.18.1</version></dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng --><dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <scope>test</scope></dependency>
Code:
package datadriven;
import org.testng.annotations.Parameters;import org.testng.annotations.Test;
public class Parametrization { @Test @Parameters({"x","y"}) public void add(int a, int b) { System.out.println("Addition of a+b:"+ (a+b)); } @Test @Parameters({"x","y"}) public void subtract(int a, int b) { System.out.println("Subtraction of a-b:" + (a-b)); } @Test @Parameters({"x","y"}) public void multiply(int a , int b) { System.out.println("Subtraction of a*b:" + (a*b)); }}
Now, generate the testing.xml file by clicking on the above “Parameterization.java” class, selecting “TestNG,” and selecting “convert to TestNG.”
Code:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"><suite name="Suite"><parameter name="x" value="10"></parameter><parameter name="y" value="8"></parameter> <test thread-count="5" name="Test"> <classes> <class name="datadriven.Parametrization"/></classes> </test> <!-- Test --></suite> <!-- Suite -->
Now, run the testng suite, then we get the output as below.
Output:
[RemoteTestNG] detected TestNG version 7.4.0
Addition of a+b:18
Subtraction of a*b:80
Subtraction of a-b:2
===============================================
Suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================
In the above code, we have created three test methods , add, subtract and multiply. These methods taking integer argument to test the operation. And in the testing.xml file , we have provided these integers to those test methods with the help of testng annotation “@parameters”
Using DataProvider annotation
The DataProvider annotation stands out as a robust tool for implementing Parameterization seamlessly. This annotation, primarily associated with TestNG, a popular testing framework, empowers testers to inject various data sets into their test methods, executing the same test logic with different parameters.
The DataProvider annotation in TestNG allows testers to define methods that supply data to test methods. These data providers can retrieve data from various sources such as arrays, lists, CSV files, Excel sheets, or databases. TestNG invokes the data provider method and passes the retrieved data to the corresponding test method, enabling parameterized test execution.
Before understanding the code to understand the DataProvider annotation, you must include the below dependencies in the pom.xml file.
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver --><dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-chrome-driver</artifactId> <version>4.18.1</version></dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --><dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.18.1</version></dependency>
<!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager --><dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>5.7.0</version></dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng --><dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <scope>test</scope></dependency>
In the testing.xml file, include the below code.
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"><suite name="Suite"> <test thread-count="5" name="Test"> <classes> <class name="datadriven.DataProviderExample"/></classes> </test> <!-- Test --></suite> <!-- Suite -->
Let's start now to code our program to understand the DataProvider annotation. Create a Java class; in the below, the “DataProviderExample” class is created. In this class, we have made two methods.
- comapnyData: This is a DataProvider method, which provides data to our test case method.
- Infoedgegroup: In this method, we have define test case to test each data we get from companyData.This method open google chrome, write company and domain in the searchbox then click to search, if we getting the result, it means our program passed all the three data sets.
Code:
package datadriven;
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.testng.annotations.DataProvider;import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataProviderExample { @DataProvider(name="infoedgecompanies") public Object[][] companyData(){ Object[][] companies=new Object[3][2]; companies[0][0]="Naukri"; companies[0][1]="job portal"; companies[1][0]="Shiksha online"; companies[1][1]="articles"; companies[2][0]="AmbitionBox"; companies[2][1]="reviews"; return companies; } @Test(dataProvider="infoedgecompanies") public void infoedgegroup(String company,String domain) { //Launch chrome browser WebDriverManager.chromedriver().setup(); WebDriver driver=new ChromeDriver(); //open url driver.get("https://www.google.com/"); //finding element searchbox by name WebElement searchbox= driver.findElement(By.name("q")); //writing company name on search box searchbox.sendKeys(company+ " "+ domain); //finding element search button by name WebElement searchbtn=driver.findElement(By.name("btnK")); //clicking on the search button searchbtn.submit(); }
}
Through output, we learned that our program ran three test cases to test three different data sets, and all passed successfully.
Output:
[RemoteTestNG] detected TestNG version 7.4.0
SLF4J(W): No SLF4J providers were found.
SLF4J(W): Defaulting to no-operation (NOP) logger implementation
SLF4J(W): See https://www.slf4j.org/codes.html#noProviders for further details.
===============================================
Suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================
Best Practices for Parameterization
- Keep test data separate from test logic to promote maintainability and reusability.
- Choose an appropriate Parameterization strategy based on the complexity of test data and the project's requirements.
- Ensure input data is validated to prevent erroneous test results from invalid or unexpected values.
- Implement logging and reporting mechanisms to track test execution and outcomes using parametrized tests.
Conclusion
Parameterization is a powerful technique in Selenium test automation, offering reusability, scalability, and flexibility to test suites. By dynamically passing data to test scripts, Parameterization enhances efficiency and improves test coverage, ultimately contributing to delivering high-quality software. Testers should embrace Parameterization as a fundamental aspect of their Selenium automation strategy, leveraging its benefits to streamline testing efforts and ensure the reliability of web applications in diverse scenarios.
Contributed By: Shubham
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio