Data providers help run the same test many times with different data. This saves time and finds more bugs.
0
0
Data providers for parameterization in Selenium Java
Introduction
When you want to test a login form with many username and password pairs.
When you need to check a calculator app with different numbers.
When you want to test a search feature with various keywords.
When you want to run the same test on different browsers or settings.
Syntax
Selenium Java
@DataProvider(name = "dataName") public Object[][] dataMethod() { return new Object[][] { {"data1", "data2"}, {"data3", "data4"} }; } @Test(dataProvider = "dataName") public void testMethod(String param1, String param2) { // test steps }
The method with @DataProvider returns a 2D Object array with test data.
The test method uses the dataProvider attribute to link to the data method.
Examples
This example tests login with two sets of username and password.
Selenium Java
@DataProvider(name = "loginData") public Object[][] loginData() { return new Object[][] { {"user1", "pass1"}, {"user2", "pass2"} }; } @Test(dataProvider = "loginData") public void testLogin(String username, String password) { // test login with username and password }
This example tests a search feature with three different keywords.
Selenium Java
@DataProvider(name = "searchTerms") public Object[][] searchTerms() { return new Object[][] { {"apple"}, {"banana"}, {"cherry"} }; } @Test(dataProvider = "searchTerms") public void testSearch(String keyword) { // test search with keyword }
Sample Program
This test checks if the sum of two numbers matches the expected result. It runs three times with different numbers.
Selenium Java
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SampleTest { @DataProvider(name = "numbers") public Object[][] numbers() { return new Object[][] { {2, 3, 5}, {10, 20, 30}, {5, 7, 12} }; } @Test(dataProvider = "numbers") public void testSum(int a, int b, int expectedSum) { int actualSum = a + b; assert actualSum == expectedSum : "Sum mismatch: expected " + expectedSum + " but got " + actualSum; System.out.println("Test passed for inputs: " + a + ", " + b); } }
OutputSuccess
Important Notes
Always name your data provider methods clearly to match their purpose.
Data providers can return any object types, not just strings or ints.
Use assertions inside the test method to check results for each data set.
Summary
Data providers let you run one test many times with different data.
This helps find bugs that happen only with certain inputs.
Use @DataProvider annotation and link it to your test method.