This post was most recently updated on July 29th, 2024
TestNG @Parameters
One of the important features of TestNG is parameterization. This annotation allows the user to pass parameter values to test methods through the testng.xml file.
@Parameters({“param-name”})
Let’s write a simple example of passing parameters to test methods through the XML configuration file.
Steps to Perform: Open chrome and enter the Demo site URL(http://thedemosite.co.uk/login.php).
2. Enter username & password then click on login button.
3. Create TestNG XML file and pass a parameter from it.
4. Close the browser.
package Parameterization;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class LoginSample {
WebDriver driver;
@BeforeTest
public void BeforeTest(){
System.setProperty(“webdriver.chrome.driver”, “D:\\chromedriver.exe”);
driver = new ChromeDriver();
driver.get(“http://thedemosite.co.uk/login.php”);
}
@Test
@Parameters({“username”,”password”})
public void Test(String username,String password){
driver.findElement(By.xpath(“//input[@name=’username’]”)).sendKeys(username);
driver.findElement(By.xpath(“//input[@name=’password’]”)).sendKeys(password);
driver.findElement(By.xpath(“//input[@name=’FormsButton2′]”)).click();
}
@AfterTest
public void AfterTest() throws InterruptedException{
Thread.sleep(3000);
driver.close();
}
}
In the above code, for Test Method ‘Test’, we are passing two parameters ‘username’ and ‘password’ as input to ‘Test’ method. The parameter needs to be passed to the test method at the time of Test execution. The value of the parameter is defined in the TestNG XML file.
Image: OptionalParameter Output
@Parameters and @Optional annotations in TestNG
In this annotation, if the defined parameter is not found in the testng.xml file, Then Test method will receive the default value from the @Optional annotation.
@Optional(“param-name” String value)
package Parameterization;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class OptionalParameter {
@Parameters({“Test1”})
@Test
public void Parameter1(String Test1){
System.out.println(“Parameter is: “+Test1);
}
@Parameters({“Test2”})
@Test
public void Parameter2(String Test2){
System.out.println(“Parameter is: “+Test2);
}
@Parameters({“Test3”})
@Test
public void Parameter3(@Optional(“Optional Parameter”) String Test3){
System.out.println(“Parameter is: “+Test3);
}
}
In the above testng.xml file, we have commented the third parameter will check the use of @Optional annotation and Let’s check the below output
In this topic, we have covered @Parameters & @Optional annotations in TestNG with a basic sample code.
In the next topic, we will start will the Listeners in TestNG.