HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TestNG / TestNG @DataProvider – Test parameters example

TestNG @DataProvider – Test parameters example

An important features provided by TestNG is the testng DataProvider feature. It helps you to write data-driven tests which essentially means that 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. It helps in providing complex parameters to the test methods as it is not possible to do this from XML.

To use the DataProvider feature in the 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.

1. TestNG @DataProvider and @Test in same class

The below test class contains a test method which takes one argument as input and prints it to 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 above test. Output of above test run is given below:

Data is: data one
Data is: data two

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

As you 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 passed by the DataProvider method, in this case as two different sets of data were returned by the DataProvider, the test method was executed two times.

It is mandatory for a @DataProvider method to return the data in the form of double array of Object class (Object [][]). The first array represents a data set where as the second array contains the parameter values.

2. TestNG @DataProvider and @Test in different classes

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

2.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" } };
	}
}

2.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);
	}
}

2.3. Demo

Now run above test. Output of above test run is given below:

Data is: data one
Data is: data two

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

As you 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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Subhu

    April 13, 2020

    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!

  2. Datta

    December 19, 2019

    Thank you so much buddy!. You made my day.

  3. Sanjay

    November 1, 2019

    Good explanation!! Thank you..

  4. Poornima

    June 1, 2019

    Can you please explain how to use this DataProvider to take data from an excel sheet?

  5. Tanushri Mukherjee

    July 17, 2017

    On Exuting the above SameClassDataProvider example I get the below error.
    How to resolve?

    [TestNG] Running:
    C:\Users\Tanushri\AppData\Local\Temp\testng-eclipse-1096063707\testng-customsuite.xml

    SKIPPED: testMethod
    org.testng.TestNGException:
    Method public void testNGProject.SameClassDataProvider.testMethod(java.lang.String) requires a @DataProvider named : data=provider
    at org.testng.internal.Parameters.findDataProvider(Parameters.java:263)
    at org.testng.internal.Parameters.handleParameters(Parameters.java:419)
    at org.testng.internal.Invoker.handleParameters(Invoker.java:1270)
    at org.testng.internal.Invoker.createParameters(Invoker.java:985)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1075)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)

    ===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 1
    ===============================================

    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 1
    ===============================================

    [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 16 ms
    [TestNG] Time taken by org.testng.reporters.jq.Main@3b6eb2ec: 69 ms
    [TestNG] Time taken by org.testng.reporters.EmailableReporter2@7a0ac6e3: 8 ms
    [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@43a25848: 36 ms
    [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@2d6e8792: 7 ms
    [TestNG] Time taken by org.testng.reporters.XMLReporter@5b464ce8: 6 ms

  6. Vivek Malhotra

    August 8, 2016

    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 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);
        }
    
  7. Himansu

    July 26, 2016

    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?

  8. rashmeemayee mohapatra

    May 27, 2016

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

  9. Abhinay

    December 29, 2015

    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?

    • Lokesh Gupta

      December 29, 2015

      It’s for executing the testcases, and adding listner to watch the execution events in Listener class.

Comments are closed on this article!

Search Tutorials

TestNG Tutorial

  • TestNG – Introduction
  • TestNG – Hello World
  • TestNG – Maven
  • TestNG – Annotations
  • TestNG – Expected Exception
  • TestNG – Disable/Ignore Tests
  • TestNG – Parallel Tests
  • TestNG – Dependent Tests
  • TestNG – Timeout Tests
  • TestNG – @Parameters
  • TestNG – @DataProvider
  • TestNG – @Factory
  • TestNG – @DataProvider
  • TestNG – Before and After
  • TestNG – Test Groups

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces