0
0
Selenium Javatesting~15 mins

First Selenium Java test - Build an Automation Script

Choose your learning style9 modes available
Verify Google Search Page Title
Preconditions (2)
Step 1: Open Chrome browser
Step 2: Navigate to 'https://www.google.com'
Step 3: Wait until the page is fully loaded
Step 4: Get the page title
✅ Expected Result: The page title should be 'Google'
Automation Requirements - Selenium WebDriver with JUnit 5
Assertions Needed:
Verify the page title equals 'Google'
Best Practices:
Use WebDriverManager to manage driver binaries
Use explicit waits to wait for page load
Use JUnit 5 assertions
Close the browser after test
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Not using explicit waits and immediately asserting the title
Hardcoding the path to ChromeDriver instead of using WebDriverManager
Not closing the browser after the test
Using JUnit 4 annotations with JUnit 5 imports
Bonus Challenge

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'.

Show Hint