First Selenium Java test - Build an Automation Script
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.By; public class GoogleTitleTest { private WebDriver driver; private WebDriverWait wait; @BeforeEach public void setUp() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); wait = new WebDriverWait(driver, java.time.Duration.ofSeconds(10)); } @Test public void testGoogleTitle() { driver.get("https://www.google.com"); // Wait until the Google Search button is visible to ensure page loaded wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("btnK"))); String title = driver.getTitle(); assertEquals("Google", title, "Page title should be 'Google'"); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
This test uses JUnit 5 and Selenium WebDriver to open Chrome and navigate to Google.
We use WebDriverManager to automatically manage the ChromeDriver binary, so no manual setup is needed.
The @BeforeEach method sets up the driver and explicit wait.
The test method opens the URL, waits explicitly for the Google Search button to appear, ensuring the page is loaded.
Then it gets the page title and asserts it equals "Google" using JUnit's assertEquals.
The @AfterEach method closes the browser to clean up.
This structure follows best practices: explicit waits, proper setup/teardown, and clear assertions.
Now add data-driven testing to verify page titles for three different URLs: 'https://www.google.com', 'https://www.bing.com', and 'https://www.yahoo.com'.