Data Providers

Data Provider is another way of parameterization in TestNG. It allows the user to pass more complex data to test case. These data can be of java objects or from external sources. In the following example you can see how a data provider is used to parameterize the user information to the test case.


Java
Copy
package org.example;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderExample {
    @Test(dataProvider = "dataPrviderExample")
    public void ExampleTestMethod(String firstName, String lastName, int age)
    {
        System.out.println("First Name is " + firstName);
        System.out.println("Last Name is " + lastName);
        System.out.println("Age is " + age);
    }
    @DataProvider(name = "dataPrviderExample")
    public static Object[][] UserData() {
        return new Object[][] {{"James", "Smith", 26}, {"John", "Ioannidis", 76}, {"Marie", "Curie", 66}};
    }
}

In the above example, a @dataprovider annotation is added to UserData method. It will take a name as string which exposes it identity to the class. All the test methods in the class can use this name to attach this data provider to their test to receive the parameters from the data source. The data provider by default returns two-dimensional array of objects. Within this data provider file, you can return static data or return data from an external file.

I you run the above test, it will perform three iteration and will print all the information passed to the test method as we have given three entries of user information.