Explain DataProviders in TestNG using an example. Can I call a single data provider method for multiple functions and classes?

DataProvider is a TestNG feature, which enables us to write DataDriven tests. When we say, it supports DataDriven testing, then it becomes obvious that the same test method can run multiple times with different data-sets. DataProvider is in fact another way of passing parameters to the test method.

@DataProvider marks a method as supplying data for a test method. The annotated method must return an Object[] where each Object[] can be assigned to parameter list of the test method.

To use the DataProvider feature in your tests, you have to declare a method annotated by @DataProvider and then use the said method in the test method using the "dataProvider" attribute in the Test annotation.

As far as the second part of the question is concerned, Yes, the same DataProvider can be used in multiple functions and classes by declaring DataProvider in separate class and then reusing it in multiple classes.

Example

@DataProvider(name="UserDetails")
public Object[][] getDataFromDataprovider()
{
    return new Object[][]
    {
        { "Ram", "India" },
        { "John", "UK" },
        { "Ben", "USA" }
    };
}


@Test(dataProvider="UserDetails")
public void testMethod(String name, String country)
{
}