DataProvider in TestNG

In the previous post, we have learnt about parameters annotation in TestNG.In this post , we will learn another way to perform parameterization in TestNG.

Apart from Parameters, there is another way to achieve parameterization which is by using DataProvider in TestNG.

DataProviders are used for data driven testing which means same test case can be run with different set of data. It is very powerful feature of TestNG and effectively used during framework development. There are few points you should know about dataProvider.

  • It marks a methods for supplying the data to other methods.
  • Annotated methods return an array of Object i.e. Object[][].
  • DataProvider can have a name, and it will be used in other methods by using its name.
  • DataProvider can be implemented in the same class or different class.
  • A Data Provider is a method annotated with @DataProvider.

We will understand the functionality of dataProvider with 2 examples.

DataProvider used in the Same Class: DataProvider can be implemented in the same class where the function using the dataProvider is residing. In the example, a class(ExampleDataProvider) is having a @Test method (TestLogin) as well as @DataProvider method(getData).

The @DataProvider method(getData) is returning an object array containing email ids and passwords.

The @Test method(TestLogin) is receiving data from dataProvider by using its name (LoginDataProvider).

Attention

@Test method must have the same no. of arguments as per the columns in the Object array returned by the DataProvider.

 

Object Array

Code:

Output:

Dataprovider result

Dataprovider testNG result

 

As you can observe in the output that TestLogin method has been executed 2 times with different set of data passed from DataProvider.


 

DataProvider used in the different class: Now, we will see if we keep method annotated with @DataProvider in another class, then how to use it. Suppose,we have 2 classes named as “ExampleDataProvider” where @Test method is present and “CustomDataProvider” where @DataProvider is present.

We will use the same @DataProvider as used in previous example, but put it in different class.

Class 1: 

Color change in excel POI

If DataProvider is implemented in another class, then annotated method should be static. (Refer Class 1)

Class 2:

Output: TestLogin will be executed with 2 set of data.

Dataprovider testNG result

 


 

Syntax for Defining a Constraint :
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Parameters in TestNG
Listeners in TestNG
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...