In this section, we will set up Selenium test automation with the TestNG framework using the Page Object Model (POM) pattern.
Setting up the Project
1. Create a Java project in your IDE.
2. Use Maven or Gradle as your build tool, depending on your preference.
3. Add Selenium WebDriver and TestNG to your project dependencies.
4. Place chromedriver.exe in the project root directory
pom.xml
Example Selenium TestNG Script
Create a class in the project and use the example script below to see how Selenium works with TestNG.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.*;
import time. Duration;
public class SeleniumTestNGTest {
WebDriver driver;
@BeforeSuite
public void beforeSuite() {
System.out.println("Before Suite: Setup environment or report or DB connection");
}
@BeforeTest
public void beforeTest() {
System.out.println("Before Test: Test-level setup");
}
@BeforeMethod
public void setup() {
System.out.println("--- Before Method: Launching browser ---");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get("https://www.qafeast.com/");
}
@Test
public void searchBoxTest() {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Accept Cookies
WebElement acceptCookie = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("gdpr-cookie-accept")));
acceptCookie.click();
// Click on Tools
WebElement toolsOption = driver.findElement(By.cssSelector("li[class='tut_ fr_tls']"));
toolsOption.click();
// Click on Demo Site link
WebElement demoSiteLink = driver.findElement(By.linkText("Demo Site"));
demoSiteLink.click();
// Verify Demo Site opened
WebElement textBoxHeading = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h2[text()='Textbox']")));
Assert.assertTrue(textBoxHeading.isDisplayed(), "'Textbox' heading is not visible on Demo Site page");
}
@AfterMethod
public void tearDown() {
System.out.println("After Method: Closing browser");
driver.quit();
}
@AfterTest
public void afterTest() {
System.out.println("After Test: Test-level teardown");
}
@AfterSuite
public void afterSuite() {
System.out.println("After Suite: Finalizing reports or sending email");
}
}
testNG.xml
Example xml file, use this to run the example script through command line or directly from IDE
GitHub Source Code: You can find a complete Selenium TestNG project in our github repository: https://github.com/qafeast/seleniumJavaPom/tree/main/src/test/java/POM