Parameterization in TestNG

  

What is Parameterization in TestNG?

Parameterization in TestNG allows us to run the same test with different sets of data. It helps in data-driven testing, where test data is separated from the test logic. TestNG provides multiple ways to do this, mainly:

  • @Parameters annotation (via testng.xml)
  • @DataProvider annotation (method-based)

1. Using @Parameters (from XML)
Pass parameters directly from the testng.xml file to your test methods.


Steps for Parameterization in TestNG

  • Define parameters in testng.xml

  • Use @Parameters in the test method

  • Use @BeforeMethod or @Test to access them



Java Code for parameterization in TestNG

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

public class ParameterExample {

    @Test
    @Parameters({"username", "password"})
    public void loginTest(String user, String pass) {
        System.out.println("Username: " + user);
        System.out.println("Password: " + pass);
    }
}



testng.xml:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="LoginTest">
    <parameter name="username" value="admin" />
    <parameter name="password" value="admin123" />
    <classes>
      <class name="ParameterExample" />
    </classes>
  </test>
</suite>



2. Using @DataProvider

We can pass multiple sets of data to a test method from a @DataProvider method.


Below is the Java Code for @DataProvider in TestNG:

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

public class DataProviderExample {

    @Test(dataProvider = "loginData")
    public void loginTest(String username, String password) {
        System.out.println("Testing with Username: " + username + ", Password: " + password);
    }

    @DataProvider(name = "loginData")
    public Object[][] getData() {
        return new Object[][] {
            {"admin", "admin123"},
            {"user", "user123"},
            {"guest", "guest123"}
        };
    }
}

No comments:

Post a Comment