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.
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.
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(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com/testpage | Page loads with header containing <h1>Welcome to Testing</h1> | - | PASS |
| 3 | Finds element using absolute XPath /html/body/div[2]/div[1]/h1 | Element located with text 'Welcome to Testing' | Element is found and text is retrievable | PASS |
| 4 | Finds element using relative XPath //div[@class='header']/h1 | Element located with text 'Welcome to Testing' | Element is found and text is retrievable | PASS |
| 5 | Asserts element text from absolute XPath equals 'Welcome to Testing' | Text matches expected value | assertEquals passes | PASS |
| 6 | Asserts element text from relative XPath equals 'Welcome to Testing' | Text matches expected value | assertEquals passes | PASS |
| 7 | Test ends and browser closes | Browser window closed | - | PASS |