How to Use DataProvider in TestNG for Automated Testing (With Examples)
Sauce AI for Test Authoring: Move from intent to executing in minutes.|xBack to ResourcesBlogPosted
Sauce AI for Test Authoring: Move from intent to executing in minutes.
|
x
Blog
How to Use DataProvider in TestNG for Automated Testing (With Examples)
Learn the fundamentals of using DataProvider for machine-controlled examination.
As the volume of applications increases, software testing teams find themselves overburdened with a “ combinatorial explosion ” of permutations for their test cases. In the early years, we hard-coded our test instance with the most important workflow, and we wrote bespoke mechanization scripts, each one to handle its own particular use case. We probably still do this more than we should if we ’ re being honest.
We need to up-level our thinking. What if, rather of 15 scripts to handle 15 slightly different scenarios, we wrote one hand, but so shoot 15 (or 50 or 500) sets of data into it? That would allow us to iterate over the same handwriting while plugging in different variations of information. The script might become slightly more complicated to address different outcomes, but those outcomes can bepiece of the information we shoot–this way, we can reprocess code, cover more substructure, and palliate more risk.
TestNG facilitates this with a characteristic called the DataProvider. This situation will walk you through the fundamentals of the TestNG DataProvider, and explain how it can make one test into a hundred (or more!).
What is TestNG?
TestNG is a powerful Java automated essay framework, offer test cases that are organized, legible, manageable, and user-friendly. It countenance sophisticated test case direction, tagging/grouping of tests, parallel execution, robust reporting, integration with all major CI/CD platforms, event-driven action, and it has a large and vibrant community supporting it.
Our examples will show test cases created employ Selenium command and written in Java.
When performingcross-browser testingacross numerous devices, browsers, and version, TestNG provides scalable automation essay capabilities through the DataProvider, allowing you to run one snippet of code multiple multiplication with the DataProvider, on hundreds of browser/OS combination. This way you can become one snippet of code into an army!
Why Use DataProvider in TestNG?
Testers use a DataProvider to pass strings or more complex parameters (such as target get from a property file or a database) into a test method. Normally, test method have void parameters:
1@Test2publicvoidnormalTest () {3//do something normal4}5// The test is then hold to use only what it already has access to, which typically means a bunch of data creation argument declared in local variables (or hard-coded into the other method call):6@Test7publicvoidloginTest () {8String username = “ first.last ”;9String password = “ abc @ 123 $ passing ”;10loginPage.login (username, password);11Assert.assertTrue (& lt; something indicating the user logged in & gt;);12}13
This results in a series of tests that look like to each other, with tenuous variations on the data you ’ re make, like loginTest1, loginTest2, loginTest3 (or hopefully more descriptive names like loginValidUser, loginInvalidUser, loginAdmin).
With TestNG ’ s DataProvider, you can indite this piece of codification only once (including whether or not it should fail), and then make the information itself do the heavy lifting. This signify much less code to debug, lots leisurely diagnosis of failure, and the possibility of feature non-coders employment through the test cases–all they ’ d receive to do is manage the DataProvidersinput.
This accelerates test development while ameliorate the accuracy of the test cases, especially when you action the tests in parallel. For example, when using a DataProvider, a single execution of a exam suite enable you to pass multiple parameters in the form of object, lyric, vectors, or numbers.
Types of Parameterization in TestNG
TestNG employs two techniques for passing parameter to your tests:
TestNG parameterization via testng.xml (or testng.yml–these model will use xml)
TestNG parameterization via DataProvider method (in code)
TestNG parameterization via TestNG.xml
Using TestNG parameterization via testng.xml, you construct basic parameters in the testng.xml file, then supply values to any test purpose & # x27; s argument leaning in the source files. The parameters specified in the testng.xml file are so referenced through the @ Parameters annotation.
This method is preferred if you receive to generate the data for your trial programmatically, or if the people keep your tests are uncomfortable working with the Java codification instantly. TestNG offers both XML and YML formats, which you can use interchangeably at your comfort level.
Here ’ s an example of how to use the testng.xml approaching for search for products in an imaginary eCommerce site:
There ’ s a class called TestProductSearch.java, which has access to basic lookup methods (searchProduct and productExists).
We add a test method–searchTest () –which should accept a twine representing the product we ’ re looking for as a parameter, and a boolean representing whether the product is valid or not (this allows you to test positive and negative suit).
This test will be action 3 time: once per “ test ” entry in testng.xml. Note that, since we ’ re cater a boolean varying indicating whether or not we expect the search to return a positive or negative answer, we have a method telephone productExists that will return true or mistaken to that effect.
Include the @ Parameters (& quot; product & quot;) annotation, which reference the name of the production supplied from the testng.xml file.
Define the
productNamedimension and its corresponding value in the testng.xml file.For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
1//TestProductSearch.java file2packet sampleTestNGPackage;3import org. testng.annotations.Parameters;4import org. testng.annotations.Test;5public class TestProductSearch {6@Test7@ Parameters (& quot; production & quot;)8public void searchTest (String productName, boolean shouldExist) {9// searches the situation for the ware specified10searchProduct (productName);11Assert.assertEquals (productExists (productName), shouldExist);12}13}
This is what our sample testNG.xml file looks like:
1//testng.xml2<?xml version=& quot; 1.0 & quot; encoding =& quot; UTF-8 & quot;?>3<!DOCTYPE suite SYSTEM& quot; http: //testng.org/testng-1.0.dtd & quot;>45<suite name=& quot; productSearchSuite & quot;>6<test name =& quot; testPencilSkirt & quot;>7<argument gens=& quot; productName & quot; value=& quot; pencil skirt & quot;/>8<parameter gens=& quot; shouldExist & quot; value=& quot; true & quot;/>9<classes>10<classname =& quot; sampleTestNGPackage.TestProductSearch & quot;/>11</classes>12</test>1314<test name =& quot; testBackpack & quot;>15<parameter gens=& quot; browserName & quot; value=& quot; backpack & quot;/>16<argument name=& quot; shouldExist & quot; value=& quot; true & quot;/>17<classes>18<classname =& quot; sampleTestNGPackage.TestProductSearch & quot;/>19</classes>20</test>2122<test name =& quot; testFrenchBread & quot;>23<parameter name=& quot; browserName & quot; value=& quot; French Bread & quot;/>24<argument name=& quot; shouldExist & quot; value=& quot; false & quot;/>25<classes>26<classname =& quot; sampleTestNGPackage.TestProductSearch & quot;/>27</classes>28</test>29</suite>
Imagine how complicated a search locomotive like this would actually be to examine. Then imagine how much redundant work would have to be performed if you had to hard code all of the tryout with declamatory datasets and argument into a individual file.
Better yet, this testng.xml file could be auto-generated by someone on the Business Analytics team, permit you to test a different set of search results every clip, using real-world user data!
TestNG parameterization via DataProvider
Sometimes it ’ s best to just work in the code. If you ’ re modeling your trial cases in the like place, and the team is comfy managing the test data thither, here ’ s how it ’ s done:
1@ DataProvider (name = & quot; name_of_dataprovider & quot;, parallel = true)2public Object [] [] testMethodName () {3returnnew Object [] [] {4{& quot; First_testcase_value & quot;},5{& quot; second_testcase_value & quot;},6{& quot; Nth_testcase_value & quot;}7}8}
In the syntax above, the@ DataProvidernote indicates that the DataProvider method is a freestanding function from the examination method, and takes the default argument:
Name: The name of a specific datum supplier.
nameis also used to bespeak data via the@Testmethod annotated with the@ DataProvider. If the gens argument in@ DataProvideris left blank, the DataProvider ’ s method gens will be used by nonremittal.Parallel: If this is set to
true, the test method annotated with@ DataProviderwill run concurrently. The default value isfalse, which mean that it will execute serially.
NOTE: The “ parallel ” parameter here will really fork a freestanding TestNG process, without adhering to the “thread-count” argument in your testng.xml file. For example, if thread-count delimitate 10, and each of your test example has 10 wrangle of DataProvider remark, you will actually run 100 tests in analogue! This can be a good thing, but make certain it ’ s well-understood within the concurrence limit of your performance platform.
The DataProvider method must be set to retrovert a 2D array of target – thus theObject [] []in the declaration.
How to Use DataProvider in TestNG (with Code Examples)
You can use a DataProvider in a variety of ways, depending on your use case and job logic. Let & # x27; s conduct a face at some real examples of how a DataProvider can be used in TestNG.
Defining DataProvider in TestNG within the same class
This is the most aboveboard method of utilizing the DataProvider. In this example, we define the DataProvider (annotated with@ DataProvider) and tryout method (annotated with@Test) within the class.
First, we & # x27; ll make a Java test class calledDataProviderTester.java.
Within the same class, we will define a method calledgetUserDetails ()that uses the@ DataPovidernotation and revert a 2D array of the user target.
We then write atestUser ()method with the@Testnotation that maps to the previous method and print out the user data.
The codification for this is as follows:
1//DataProviderTester.java23import org.testng.annotations.DataProvider;4import org.testng.annotations.Test;5signification User from ./src/User.java;6public class DataProviderTester {78@ DataProvider (gens = & quot; user_test1 & quot;)9public motionless Object [] [] getUserDetails () {10returnnew Object [] [] {{new User (& quot; Jane Done & quot;, & quot; Female & quot; ,21)}};11}12@ Test (dataProvider = & quot; user_test1 & quot;)13public vacancy testUser (User myUser) {14System.out.println (myUser.name + & quot; & quot; + myUser.gender + & quot; & quot; + myUser.age);15}16}
NOTE: This example actually sends instantiated Java Objects to the test method, which can give you a lot more power and tractableness than hard-coded twine, integer, or other uncomplicated data eccentric.
Inheriting DataProvider in TestNG
DataProvider can also be inherited, in which event the Test and DataProvider method are written in freestanding classes. This is a common strategy when indite codification (particularly when dealing with huge datasets and various test cases) because it helps with code reusability, modularization, and readability.
The following code shows you how to construct a utility class (dataProviderClass) that preserve multiple DataProviders. Importantly, it can likewise be used to pass trial data via the class property.
1// DataProviderClass.java2package sampleNestedPackage;3import org.testng.annotations.DataProvider;45public form DataProviderClass {67@ DataProvider (name = & quot; data-provider & quot;)8public static Object [] [] dataProviderMethod () {910return new Object [] [] {{& quot; first Object & quot;}, {& quot; 2nd Object & quot;}};11}12}
Passing multiple parameter values to DataProvider
We can besides pass multiple parameter values to DataProvider as a single argument so that a string of inputs can be accomplish in one go. For exemplar, the following test case ascertain whether the third argumentation is adequate to the sum of the 1st two integers:
1//DProviderClass.java23import org.testng.annotations.Test;4significance org.testng.annotations.DataProvider;5import org.testng.Assert;67public course DProviderClass {89@ DataProvider (name = & quot; data-provider & quot;)10public Object [] [] dpMethod (String datum) {11returnnew Object [] [] {{13,3,16}, {3,6,9}, {4,7,10}};12}1314@ Test (dataProvider = & quot; data-provider & quot;)15public void myTest (int numOne, int numTwo, int theSum) {1617int sum = numOne + numTwo;1819Assert.AssertEquals (theSum, sum);20}21}
As you can see in the code above, we utilized DataProvider in TestNG to aggregate multiple value into a single argument instead than portion values one at a time.
Getting Started with DataProvider in TestNG for Automated Testing
In this clause, we showed you how to use TestNG parameter like DataProvider to execute test scripts. When you have a large number of permutations and combinations to test, you can use TestNG ’ s DataProvider instead of hard encrypt the test value in the scripts.
Since TestNG can consent external files, DataProvider can be expend to run tryout with legion parameters, which is particularly useful with functional test automation model like.
Organizations should aim to optimize testing by running parallel tests and leveragingautomate testingthrough TestNG.
Sauce Labscan help you with a wide variety of automated testing needs.Sign up for a Sauce Labs free trialto start testing today.
Need to test right now? Get started costless.
Ship code that behaves exactly as it should, quicker.
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free