HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

TestNG @DataProvider – Test parameters example

By Lokesh Gupta | Filed Under: TestNG

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 !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

8
Leave a Reply

This comment form is under antispam protection
7 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Sanjay

Good explanation!! Thank you..

Vote Up0Vote Down  Reply
1 month ago
Poornima

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

Vote Up0Vote Down  Reply
6 months ago
Tanushri Mukherjee

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

Vote Up0Vote Down  Reply
2 years ago
Vivek Malhotra

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);
    }
Vote Up0Vote Down  Reply
3 years ago
Himansu

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?

Vote Up0Vote Down  Reply
3 years ago
rashmeemayee mohapatra

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

Vote Up0Vote Down  Reply
3 years ago
Abhinay

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?

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
3 years ago

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

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz