0
0
Selenium Javatesting~15 mins

TestNG annotations (@Test, @BeforeMethod, @AfterMethod) in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify Google Search page title
Preconditions (3)
Step 1: Open Chrome browser
Step 2: Navigate to https://www.google.com
Step 3: Verify the page title is 'Google'
Step 4: Close the browser
✅ Expected Result: The browser opens Google homepage, the title is exactly 'Google', and browser closes after verification
Automation Requirements - TestNG with Selenium WebDriver
Assertions Needed:
Assert that the page title equals 'Google'
Best Practices:
Use @BeforeMethod to set up WebDriver and open browser
Use @Test to perform the title verification
Use @AfterMethod to close the browser
Use explicit waits if needed (not required here)
Use meaningful method names
Automated Solution
Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class GoogleTitleTest {
    private WebDriver driver;

    @BeforeMethod
    public void setUp() {
        // Initialize ChromeDriver
        driver = new ChromeDriver();
        // Open Google homepage
        driver.get("https://www.google.com");
    }

    @Test
    public void verifyGoogleTitle() {
        // Get the page title
        String title = driver.getTitle();
        // Assert title is exactly 'Google'
        Assert.assertEquals(title, "Google", "Page title should be 'Google'");
    }

    @AfterMethod
    public void tearDown() {
        // Close the browser
        if (driver != null) {
            driver.quit();
        }
    }
}

The @BeforeMethod annotation marks the setUp() method to run before each test. It initializes the ChromeDriver and opens the Google homepage.

The @Test annotation marks verifyGoogleTitle() as the test method. It fetches the page title and asserts it equals 'Google'.

The @AfterMethod annotation marks tearDown() to run after each test. It closes the browser to clean up.

This structure ensures the browser opens fresh for each test and closes afterward, keeping tests independent and clean.

Common Mistakes - 4 Pitfalls
Not closing the browser in @AfterMethod
Initializing WebDriver inside the @Test method
Using Thread.sleep instead of proper waits
Not using assertions to verify the title
Bonus Challenge

Now add data-driven testing with 3 different URLs and verify their titles

Show Hint