TestNG Data Provider to pass parameters to the test methods is explained in this post. Parameters to the test methods can be passed from XML file is explained in previous post, refer TestNG Parameter from XML
TestNG Data Provider
- Data Provider is used to pass parameters that needs to be created from Java (Object read from a property file or a data base)
- Data Provider is a method in a same class or one of it’s super class that returns an array of array of objects(Object ) to supply the values that needs to test.
- First dimension size represents the number of times test methods needs to be invoked
- Second dimension size represents the array of objects that must be compatible with the test method parameter types
- To get parameters with Data Provider on a test method, use annotation @DataProvider
- Annotation @DataProvider has a name attribute @DataProvider(name=”…”), this name will be used in a test method with dataprovider attribute @Test(dataprovider= “…”)
- If Data Provider don’t have name attribute, name of the method will be used to refer to it
Below is the sample code used for Data Provider to pass the values to the test methods.
- Method “data” marked as a Data Provider and named as “userDetails”, it will return two dimensional array with set of user details.
- “login” is a test method used this Data Provider to receive user details and this login method will hand over those received values to it’s parameters.
- “login” test method will be execute twice as data provider has two sets of data.
Below is the result when executed the above class.
Data Provider in a Different class
- By default Data provider will be looked in the current class or it’s super classes.
- If we want to place in a different class, it needs to be static method and
specify class name in “dataProviderClass” attribute.
Below is the example code for reference
- Removed Data Provider from the current class and placed in another class named as “ExternalDataProviderTest”
- Specified class name in @Test annotation
@Test(dataProvider = “userDetails”, dataProviderClass=ExternalDataProviderTest.class)
When executed, it will give you the same result as above.
In this post we learned how to use Data Provider to pass values for test method from the same class and from different class as well.