0
0
Selenium Javatesting~10 mins

TestNG annotations (@Test, @BeforeMethod, @AfterMethod) in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses TestNG annotations to open a browser before each test, check the page title, and close the browser after each test.

Test Code
Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;

public class TestNGAnnotationsExample {
    WebDriver driver;

    @BeforeMethod
    public void setUp() {
        // Set the path to chromedriver executable if needed
        // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        driver = new ChromeDriver();
        driver.get("https://example.com");
    }

    @Test
    public void verifyPageTitle() {
        String title = driver.getTitle();
        assertEquals(title, "Example Domain", "Page title should be 'Example Domain'");
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 3 Steps
StepActionSystem StateAssertionResult
1BeforeMethod runs: ChromeDriver is initialized and navigates to https://example.comBrowser window opens and loads the Example Domain page-PASS
2Test method runs: Gets the page titleBrowser is on Example Domain pageCheck that page title equals 'Example Domain'PASS
3AfterMethod runs: Browser is closedBrowser window closes-PASS
Failure Scenario
Failing Condition: Page title does not match 'Example Domain'
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @BeforeMethod annotation do in this test?
ACloses the browser after tests
BRuns the setup code before each test method
CRuns the test method
DSkips the test method
Key Result
Using @BeforeMethod and @AfterMethod ensures each test starts fresh with a new browser and cleans up properly, preventing side effects between tests.