TestNG provides a way to get the data from external sources like from excel/textfile/arrays which helps to prepare data driven framework in automation.
@Parameters – pass parameters from the testNG.xml
@dataProvider – Pass the parameters as a 2D array.
In this post, we will look into dataProvider
@DataProvider
This is another way of passing 2 dimensional array as parameter from a method of same or from different class, let’s see one by one.
the @Test method will run number of times depends on the number of data sets provided in the object array.
From same class
package annotationpkg;import org.testng.annotations.DataProvider;import org.testng.annotations.Test;public class dataprovider {@DataProvider(name = "data-provider")public Object[][] dataProviderArr() {//Create 2 diemensional array//can even take the data from an excel sheet or from a Map//and put it into this array variableString object[][] = { { "user1", "1234" }, { "user2", "5678" } };return object;}@Test(dataProvider = "data-provider")public void fn_Credentials(String userName, String password) {System.out.print("UserName is: " + userName);System.out.print(" | ");System.out.println("Password is: "+ password);}}
Let’s say we have the public Object[][] dataProviderArr() method defined in another class (dataProviderArray.class), then we can write:
From another class
public class dataProviderArray{@DataProvider(name = "data-provider")public Object[][] dataProviderArr() {//Create 2 diemensional array//can even take the data from an excel sheet or from a Map//and put it into this array variableObject[][] obj= { { "user1", "1234" }, { "user2", "5678" } };return obj;}
package annotationpkg;import org.testng.annotations.DataProvider;import org.testng.annotations.Test;public class dataprovider {@Test(dataProvider = "data-provider", dataProviderClass = dataProviderArray.class)public void fn_Credentials(String userName, String password) {System.out.print("UserName is: " + userName);System.out.print(" | ");System.out.println("Password is: "+ password);}}
The TestNG.xml looks like (for from same and another class)
<xml version="1.0" encoding="utf-8"?><Suite name="MySuite" parallel="none"><test name="Test1"><CLasses><class name="annotationpkg.dataprovider"/></classes></test></suite>
If you are good with the above feature, then look for the implementation with selenium, refer below –
Use dataProvider in selenium test
Pass excel data to testNG dataProvider and run selenium tests
Let’s see some more details about the testNG, @Test annotation attributes
2 Comments