TestNG Parameters Example

By Arvind Rai, April 02, 2023
On this page, we will learn using TestNG parameters in our unit test cases.
In TestNG, we can pass arbitrary number of parameters to test methods using @Parameters and @DataProvider annotations.
1. @Parameters : This annotation is used at test methods. The @Parameters defines the arbitrary number of parameters. We can pass values to parameters by testng.xml file.
2. @DataProvider : We use @DataProvider when we create test data using Java object, property file or database. To use Data Provider, we create a method annotated with @DataProvider and assign a name using its name attribute. The Data Provider name is assigned to dataProvider attribute of @Test annotation.

Here we will discuss using @Parameters and @DataProvider annotations in detail with examples.

1. Using @Parameters

The TestNG @Parameters annotation can pass arbitrary number of parameters to each of our tests. The @Parameters annotation can be used with followings.
a. @Test annotation.
b. before/after annotations such as @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeGroups, @AfterGroups, @BeforeClass, @AfterClass, @BeforeMethod, @AfterMethod.
c. @Factory annotation.
d. At most one constructor of our test class.

Now look into the code below. The @Parameters annotation has defined two parameters i.e. user_name and user_age.
@Parameters({"user_name", "user_age"})
@Test
public void userInfoTest(String name, Integer age) {
  assertTrue(name.length() > 3);
  assertTrue(age >= 18);
} 
Order of defined parameters within @Parameters annotation should be considered properly because first parameter of @Parameters is associated with first parameter of test method and second parameter of @Parameters is associated with second parameter of test method and so on.
Hence the parameter user_name is associated with name and user_age is associated with age.

We can set values to parameters by three ways.
1. The testng.xml file
2. Programmatically
3. Java system properties

1.1 Using testng.xml

In testng.xml, we can set values to parameters using <parameter> tag within <suite> or <test> tag. The parameters defined within <suite> are applicable to all <test>. If a parameter is defined within <suite> as well as a <test>, then the parameter value defined within <test> is applicable for this <test>.
Find the example.
MyTest.java
public class MyTest {
  @Parameters({ "database" })
  @BeforeClass
  public void setUp(String db) {
	System.out.println("Test setup completed: " + db);
  }

  @Parameters({ "user_name", "user_age" })
  @Test
  public void userInfoTest(String name, Integer age) {
	System.out.println("userInfoTest: " + name + ", " + age);
	assertTrue(name.length() > 3 && age >= 18);
  }

  @Parameters({ "user_role", "isActive" })
  @Test
  public void userRoleTest(String role, Boolean isActive) {
	System.out.println("userRoleTest: " + role + ", " + isActive);	
	assertTrue(role.equals("Admin") && isActive);
  }

  @Parameters({ "resource" })
  @AfterClass
  public void destroy(String resource) {
	System.out.println("Resources are released: " + resource);
  }
} 
testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="Suite1" verbose="1">
  <parameter name="database" value="Oracle" />
  <parameter name="resource" value="DB Connection" />  
  <parameter name="user_name" value="Mohan" />
  <parameter name="user_age" value="20" />
  <parameter name="user_role" value="User" />
  <test name="Regression1">
    <parameter name="user_role" value="Admin" />
    <parameter name="isActive" value="true" />      
    <classes>
      <class name="com.concretepage.MyTest" />
    </classes>
  </test>
</suite> 
To run the test in Eclipse, right click on testng.xml -> Run As ->TestNG Test.

Output
TestNG Parameters Example

1.2 Programmatically

In this example, we will create a parameterized test method and then run it programmatically.
MyTest.java
public class MyTest {
  @Parameters({ "user_role", "isActive" })
  @Test
  public void userRoleTest(String role, Boolean isActive) {
	System.out.println("userRoleTest: " + role + ", " + isActive);	
	assertTrue(role.equals("Admin") && isActive);
  }
} 
Find the code to run test method programmatically.
TestRunner.java
public class TestRunner {
  public static void main(String[] args) {
	XmlClass testClass = new XmlClass();
	testClass.setClass(MyTest.class);

	XmlSuite suite = new XmlSuite();
	suite.setName("Suite1");

	XmlTest test = new XmlTest(suite);
	test.setName("Regression1");
	test.addParameter("user_role", "Admin");
	test.addParameter("isActive", "true");
	test.setXmlClasses(Arrays.asList(testClass));

	TestNG testNG = new TestNG();
	testNG.setXmlSuites(Arrays.asList(suite));
	testNG.run();
  }
} 
Output
userRoleTest: Admin, true

===============================================
Suite1
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
=============================================== 

1.3 Java System Properties

In this example, we will pass parameters using Java system properties.
Find the parameterized test.
MyTest.java
public class MyTest {
  @Parameters({ "user_mode", "isGranted" })
  @Test
  public void userPermissionTest(String mode, Boolean isGranted) {
	System.out.println("userPermissionTest: " + mode + ", " + isGranted);	
	assertTrue(mode.equals("READ") && isGranted);
  }
} 
testng.xml
<suite name="Suite1" verbose="1">
  <test name="Regression1">
    <classes>
      <class name="com.concretepage.MyTest" />
    </classes>
  </test>
</suite> 
To pass value to parameters and run it in Eclipse, follow the steps.
1. Right click on test class or testng.xml -> Run As -> Run Configurations.
2. Click on Arguments tab. In VM arguments section, enter the following arguments.
-Duser_mode=READ -DisGranted=true 
Find the print screen.
TestNG Parameters Example
3. Click on Run. Find the output.
userPermissionTest: READ, true
PASSED: com.concretepage.MyTest.userPermissionTest("READ", true)

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

2. Using @Optional Annotation

The @Optional annotation specifies the default value for a parameter. If the value for such parameter is not defined in testng.xml, the default value is used.
The @Optional annotation is used with test method parameter as below.
@Parameters({ "userMode" })
@Test
public void grantPermissionTest(@Optional("READ") String mode) { ... } 
If userMode parameter is not configured in testng.xml, the test method will receive the default value specified inside the @Optional annotation i.e. "READ".
Find the example.
MyTest.java
public class MyTest {
  @Parameters({ "userMode", "userRole" })
  @Test
  public void grantPermissionTest(@Optional("READ") String mode, String role) {
	System.out.println("grantPermissionTest: " + mode + ", " + role);	
  }
} 
testng.xml
<suite name="Suite1" verbose="1">
  <test name="Regression1">
    <parameter name="userRole" value="SUPERVISER" />
    <classes>
      <class name="com.concretepage.MyTest" />
    </classes>
  </test>
</suite> 
Output
grantPermissionTest: READ, SUPERVISER

===============================================
Suite1
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
=============================================== 

3. Using @DataProvider

1. A data provider is a method annotated with @DataProvider that returns an array of array of objects.
2. The Data Provider is used to pass parameters when passing parameters by testng.xml might not sufficient.
3. We configure a name to Data Provider method using name attribute of @DataProvider annotation and then that name as associated to test method using dataProvider attribute of @Test annotation.
Find the sample code to use Data Provider.
MyTest.java
package com.concretepage;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class MyTest {
  @DataProvider(name = "user")
  public Object[][] createUserData() {
	return new Object[][] { 
	  { "Mohit", 20 },
	  { "Krishna", 30 },
	  { "Shiva", 25 }
	};
  }
  @DataProvider(name = "add")
  public Integer[][] createAddData() {
	return new Integer[][] { 
	  { 30, 20 }, { 40, 50 }
	};
  }  

  @Test(dataProvider = "user")
  public void userInfoTest(String name, Integer age) {
	System.out.println("userInfoTest: " + name + ", " + age);
  }
  @Test(dataProvider = "add")
  public void addTest(Integer num1, Integer num2) {
	System.out.println("addTest: " + num1 + ", " + num2);
  }  
} 
testng.xml
<suite name="Suite1" verbose="1">
  <test name="Regression1">
    <classes>
      <class name="com.concretepage.MyTest" />
    </classes>
  </test>
</suite> 
Output
addTest: 30, 20
addTest: 40, 50
userInfoTest: Mohit, 20
userInfoTest: Krishna, 30
userInfoTest: Shiva, 25

===============================================
Suite1
Total tests run: 5, Passes: 5, Failures: 0, Skips: 0
=============================================== 
4. We can use the Data Providers in the case when parameters need to be created from Java objects, data read from property files or databases.
5. Data Providers method can be created within same class of test methods or in separate class. When Data Providers are created in separate class, the Data Provider methods should be static. We can also create non-static Data Provider methods but then the class should have a no-argument constructor.
6. The Data Provider class is associated with test methods using dataProviderClass attribute of @Test annotation.
7. The Data Provider methods can return an array of array of objects (Object[][]) or an Iterator<Object[]> . Find the example.
MyTest.java
public class MyTest {
  @Test(dataProvider = "activeUser", dataProviderClass = MyDataProvider1.class)
  public void activeUserTest(String name, boolean isActive) {
   System.out.println("activeUserTest: " + name + ", " + isActive);
  }
  
  @Test(dataProvider = "userRole", dataProviderClass = MyDataProvider2.class)
  public void userRoleTest(String name, String role) {
   System.out.println("userRoleTest: " + name + ", " + role);
  }
} 
MyDataProvider1.java
public class MyDataProvider1 {
  @DataProvider(name = "activeUser")
  public static Object[][] createUserData() {
   return new Object[][] {
     { "Mahesh", true },
     { "Mohan", true},
   };
  }
} 
MyDataProvider2.java
public class MyDataProvider2 {
  public MyDataProvider2() { }

  @DataProvider(name = "userRole")
  public Iterator<Object[]> createData() {
	Object[] u1 = { "Shiva", "ADMIN" };
	Object[] u2 = { "Narendra", "USER" };
	return Arrays.asList(u1, u2).iterator();
  }
} 
Output
activeUserTest: Mahesh, true
activeUserTest: Mohan, true
userRoleTest: Shiva, ADMIN
userRoleTest: Narendra, USER

===============================================
Suite1
Total tests run: 4, Passes: 4, Failures: 0, Skips: 0
=============================================== 

4. Reference

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us