TestNG @DataProvider

An important feature provided by TestNG is the @DataProvider annotation that helps us to write repeated tests or data-driven tests. This essentially means that the same test method can be run multiple times with different data sets.

Please note that @DataProvider is the second way of passing parameters to test methods except passing parameters from testng.xml. @DataProvider helps in passing the complex parameters to the test methods as it is not possible to do with @Parameters.

1. @DataProvider

To use the @DataProvider feature in the tests, we have to declare a method annotated by @DataProvider and then use this method in the tests using the ‘dataProvider‘ attribute in the @Test annotation.

The name of the dataprovider ( ‘data-provider’ in this case ) must be used by the test method if it wants to use the datasets provided by this method.

@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod() {
	return new Object[][] { { "data one" }, { "data two" } };
}

2. Using @DataProvider and @Test in Same Test Class

The below test class contains a test method that takes one argument as input and prints it to the console when executed. A DataProvider method is also available in the same class by using the @DataProvider annotation of TestNG.

The name of the said DataProvider method is mentioned using the name attribute of the @DataProvider annotation. The DataProvider returns a double Object class array with two sets of data i.e. “data one” and “data two“.

package com.howtodoinjava.test;

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

public class SameClassDataProvider
{
	@DataProvider(name = "data-provider")
	public Object[][] dataProviderMethod() {
		return new Object[][] { { "data one" }, { "data two" } };
	}

	@Test(dataProvider = "data-provider")
	public void testMethod(String data) {
		System.out.println("Data is: " + data);
	}
}

Now run the above test.

Data is: data one
Data is: data two

PASSED: testMethod("data one")
PASSED: testMethod("data two")

As we can see from the above test result the respective test method in the class was executed two times.

The execution of the test method is dependent upon the number of data sets defined by the @DataProvider annotated method. In the above example, as two different sets of data were returned by the DataProvider, the test method was executed two times.

Note

This is mandatory for a @DataProvider method to return the data in the form of a two-dimensional array of Object class (Object [][]).

The first array represents the collection of datasets whereas the second array contains the parameter values in a particular dataset.

3. Using @DataProvider and @Test in Different Classes

If we have declared a separate class as the data provider, we need to create an static method in that class with same syntax as in the previous example.

Next, we must use the dataProviderClass attribute of the @Test annotation.

To understand this, add two classes with the names DataProviderClass and TestClass as below.

3.1. DataProvider.java

import org.testng.annotations.DataProvider;

public class DataProviderClass
{
	@DataProvider(name = "data-provider")
	public static Object[][] dataProviderMethod()
	{
		return new Object[][] { { "data one" }, { "data two" } };
	}
}

3.2. TestClass.java

import org.testng.annotations.Test;

public class TestClass
{
	@Test(dataProvider = "data-provider", dataProviderClass = DataProviderClass.class)
	public void testMethod(String data)
	{
		System.out.println("Data is: " + data);
	}
}

3.3. Demo

Now run the above test.

Data is: data one
Data is: data two

PASSED: testMethod("data one")
PASSED: testMethod("data two")

As we can see from the above test results the test method was executed two times depending upon the data passed to it by DataProvider method.

In this scenario, the DataProvider method was in a different class. In such a case the dataProviderMethod() has to be declared static so that it can be used by a test method in a different class for providing data.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

10 thoughts on “TestNG @DataProvider”

  1. The same code using in my framework.

    @DataProvider(name=”Login”, parallel = false)
    public static Object[][] dataProviderMethodLogin() {
    return new Object[][]{
    {“username1@mail.com”, “test”,”Message”},
    {“username2@mail.com”, “test”,”Message”},
    {“username3@mail.com”, “test”,”Message”},
    {“usernam4@mail.com”, “test”,”Message”}
    };
    }

    @Test(dataProvider = “Login”, dataProviderClass = DataProvider.class)
    public void testMethod(String user, String pwd, String message)
    {

    }

    In the array, first row got and ran successfully.
    {“username1@mail.com”, “test”,”Message”},

    I’m getting the error as “Tests ignored” for the remaining three in data provider.
    {“username2@mail.com”, “test”,”Message”},
    {“username3@mail.com”, “test”,”Message”},
    {“username4@mail.com”, “test”,”Message”}

    Can you please assist me on this behavior?

    Thanks!

    Reply
  2. On Executing the above SameClassDataProvider example I get the below error.
    How to resolve?

    [TestNG] Running:
    C:\Users\Tanushri\testng-customsuite.xml

    SKIPPED: testMethod
    org.testng.TestNGException:
    Method public void testNGProject. SameClassDataProvider.testMethod(java.lang.String)
    requires a @DataProvider named : data=provider

    Reply
  3. Hi @Lokesh,
    I am using Spring Junit for my tests as below. Then I had to pass test data to my @Test Method and I tried to use the TestNG Data provider depicted above.

    I added a class called “TestNGDataProvider.java” which returns test data.

    
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(TestConfiguration.class)
    public class LaxTest extends LaxBaseTest {
    
    @Before
        public void before() {
        }
    
    @Test
    public void testLax() throws Exception {
            File file= laxRemote.runLax();
            readAndVerifyLaxFile(file);
        }
    }
    

    Then when I tried to modify my below Test to use dataprovider from “TestNGDataProvider.java” as below I get error saying – java.lang.Exception: No runnable methods

    Do you know how to fix this? I guess as I am using @RunWith(SpringJUnit4ClassRunner.class) this is the problem. Do I need to use a different runner if I am running my test with TestNG @Test instead of Junit @Test

    
    import org.junit.After;
    import org.junit.Before;
    import org.testng.annotations.Test;
    import org.junit.runner.RunWith;
    @Test (dataProvider = "invoices", dataProviderClass = TestNgDataProvider.class)
        public void testLax(String invoice1, String invoice2) throws Exception {
    
            LOGGER.info("Test data is: {}, {}", invoice1, invoice2);
    
            File file= laxRemote.runLax();
            readAndVerifyLaxFile(file);
        }
    
    Reply
  4. Hi Lokesh
    To add one this i.e. Giving name to DataProvider method is optional i.e.

    @DataProvider
    public static Object[][] dataProviderMethod()
    {
    return new Object[][] { { “data one” }, { “data two” } };
    }

    @Test(dataProvider = “dataProviderMethod”)
    public void testMethod(String data) {
    System.out.println(“Data is: ” + data);
    }

    Can you also explain how to use DataProvider in reading it from a csv file?

    Reply
  5. Can we write two data providers in one test method ?if yes how ..please suggest me, i am a beginner.

    Reply
  6. TestListenerAdapter tla = new TestListenerAdapter();
    @SuppressWarnings(“deprecation”)
    TestNG testng = new TestNG();
    testng.setTestClasses(new Class[] { Runner.class });
    testng.addListener(tla);
    testng.run();
    Can you please explain this piece of code?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.