Parameterization

Many time you might come across a situation where you need to run the test case with different sets of data or dynamic data. This can be achieved through parameterization of your test cases. Through parameterization you can run the same test for different sets of data. TestNG allows us to parameterize the test case using the following ways.

  • Using testng.xml file
  • Data Provider

In this chapter we will learn parametrization using testng.xml file. For this example we need to create following files.
  • testng.xml
  • ExampleTest.java

testng.xml

XML
Copy
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="DemoTestSuite">
    <test name="Demo Test">

        <parameter name="firstName" value="James"></parameter>
        <parameter name="lastName" value="Smith"></parameter>
        <parameter name="age" value="25"></parameter>
        <classes>
            <class name="org.example.ExampleTest"/>
        </classes>
    </test>
</suite>

ExampleTest.java

Java
Copy
package org.example;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ExampleTest {
    @Test
    @Parameters({"firstName", "lastName", "age"})
    public void ExampleTestMethod(String firstName, String lastName, int age)
    {
        System.out.println("First Name is " + firstName);
        System.out.println("Last Name is " + lastName);
        System.out.println("Age is " + age);
    }
}

In the above testng.xml file we have added three parameter element with name firstName, lastName and age. To pass the parameter from xml to test case we have added @Parameters annotation for method ExampleTestMethod in the ExampleTest.java file and added reference of each parameter name. To pass these references to the test method we have added parameter in the method signature with respective data type. TestNG will automatically convert to respective data type.

Now run the testng.xml file, you will see all the parameters value will be printed.
First Name is James
Last Name is Smith Age is 25
===============================================
DemoTestSuite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
You can try with different data type as per the requirement.