0
0
Selenium Javatesting~10 mins

Absolute vs relative XPath in Selenium Java - Test Execution Compared

Choose your learning style9 modes available
Test Overview

This test opens a web page and locates the same element using both absolute and relative XPath. It verifies that both locators find the element and that the element's text matches the expected value.

Test Code - JUnit
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
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;

public class XPathTest {
    WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        driver.get("https://example.com/testpage");
    }

    @Test
    public void testAbsoluteAndRelativeXPath() {
        // Absolute XPath locator
        WebElement elementAbsolute = driver.findElement(By.xpath("/html/body/div[2]/div[1]/h1"));
        // Relative XPath locator
        WebElement elementRelative = driver.findElement(By.xpath("//div[@class='header']/h1"));

        String expectedText = "Welcome to Testing";

        assertEquals(expectedText, elementAbsolute.getText(), "Absolute XPath text mismatch");
        assertEquals(expectedText, elementRelative.getText(), "Relative XPath text mismatch");
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open and ready-PASS
2Navigates to https://example.com/testpagePage loads with header containing <h1>Welcome to Testing</h1>-PASS
3Finds element using absolute XPath /html/body/div[2]/div[1]/h1Element located with text 'Welcome to Testing'Element is found and text is retrievablePASS
4Finds element using relative XPath //div[@class='header']/h1Element located with text 'Welcome to Testing'Element is found and text is retrievablePASS
5Asserts element text from absolute XPath equals 'Welcome to Testing'Text matches expected valueassertEquals passesPASS
6Asserts element text from relative XPath equals 'Welcome to Testing'Text matches expected valueassertEquals passesPASS
7Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: Element not found using absolute XPath due to page structure change
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath type is more fragile to page structure changes?
AAbsolute XPath
BRelative XPath
CBoth are equally fragile
DNeither is fragile
Key Result
Using relative XPath is a better practice because it is less likely to break when the page layout changes, making tests more reliable.