TestNG Parameterization

Sometimes an application requires to run with the different parameters. It allows us to run the same test again and again with different test data. There are two ways to perform it.

  • Set the parameters in testng.xml file
  • With the help of data providers

1. Using testng.xml, we could define parameters in this xml file and then reference those parameters in the test files.

Let us see an example: In this example we takes a string value “browser” as a parameter whose value would be passed from testng.xml.

package testFramework;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ParameterizationTest {

  @Test
  @Parameters("browser")
  public void parameterizationTest(String browser) {
    if(browser.equals("Firefox")) {
      System.out.println("Open firefox browser");
    } else if(browser.equals("Chrome")) {
      System.out.println("Open chrome browser");
    }
  }
}

 

Let us see the testng.xml file

Output:

[RemoteTestNG] detected TestNG version 6.14.2
Open firefox browser===============================================
Parameterization Test Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

2. Passing parameters using Data providers:

Sometimes we need to add or pass complex parameters like read the objects from a property file, excel file or a database. In this case, we need a Data Provider to supply the values which we need to test. A Data Provider is a method on your class that returns an array of objects.

Let us see an example:

package testFramework;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderTest {

  @Test(dataProvider = "getData")
  public void AppTest(String userName, String pwd) {
    System.out.println("Username " + userName);
    System.out.println("Password " + pwd);
  }
  @DataProvider(name = "getData")
  public Object[][] getData() {
    
    Object testData[][] = new Object[3][2];
    testData[0][0] = "UserID1";
    testData[0][1] = "Password1";
    testData[1][0] = "UserID2";
    testData[1][1] = "Password2";
    testData[2][0] = "UserID3";
    testData[2][1] = "Password3";
    
    return testData;
  }
}

Output:

[RemoteTestNG] detected TestNG version 6.14.2
Username UserID1
Password Password1
Username UserID2
Password Password2
Username UserID3
Password Password3
PASSED: AppTest(“UserID1”, “Password1”)
PASSED: AppTest(“UserID2”, “Password2”)
PASSED: AppTest(“UserID3”, “Password3”)

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