TestNG allows the user to pass values to test methods as arguments by using parameter annotations through testng.xml file. Some times it may be required for us to pass values to test methods during run time. Like we can pass user name and password through testng.xml instead of hard coding it in test methods. or we can pass browser name as parameter to execute in specific browser.
To test the different parameters, use the @Parameters annotation in the code and parameters tag in the <XML> file to pass parameter values
package testNGFrameWork;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParametrizationUsingXMLFile {
@Parameters({ "url", "UN", "PW" })
@Test
public void loginTestCase(String url, String UN, String PW) {
System.setProperty("webdriver.chrome.driver","F:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Navigate to Orange HRM login page
driver.get(url);
// Enter the user name
driver.findElement(By.xpath("//input[@id='txtUsername']")).sendKeys(UN);
// Enter the password
driver.findElement(By.id("txtPassword")).sendKeys(PW);
// Click on login button
driver.findElement(By.id("btnLogin")).click();
// Verify home page
Assert.assertEquals(driver.findElement(By.id("welcome")).getText(), "Welcome Admin");
}
}
Now create testng.xml file as shown as below-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Parameterization Test Suite">
<test name="Testing Parameterization">
<parameter name="url" value="https://opensource-demo.orangehrmlive.com/index.php/auth/login"/>
<parameter name="UN" value="admin"/>
<parameter name="PW" value="admin123"/>
<classes>
<class name="testNGFrameWork.ParametrizationUsingXMLFile" />
</classes>
</test>
</suite>
Note:
- The parameter is declared by the parameter tag and name attribute, defines the name of the attribute and it must match the
@Parametersannotation attribute in the code, and the value defines the value of the attribute parameter. - The parameter tag can also be used at the level of the suite along with the test level.