0
0
Selenium Javatesting~10 mins

XPath with text() in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page, finds a button using XPath that matches its visible text, clicks it, and verifies the expected result appears on the page.

Test Code - JUnit with Selenium WebDriver
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 XPathTextTest {
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void testClickButtonByText() {
        driver.get("https://example.com/testpage");
        WebElement button = driver.findElement(By.xpath("//button[text()='Click Me']"));
        button.click();
        WebElement message = driver.findElement(By.id("result-message"));
        assertEquals("Button clicked!", message.getText());
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsTest framework initializes ChromeDriver-PASS
2Browser opensChrome browser window opens-PASS
3Navigates to https://example.com/testpagePage loads with a button labeled 'Click Me'Page title or URL can be checked (not shown here)PASS
4Finds button element using XPath //button[text()='Click Me']Button element with exact text 'Click Me' is locatedElement is found and not nullPASS
5Clicks the buttonButton click triggers page update-PASS
6Finds element with id 'result-message'Element showing result message is presentElement is found and not nullPASS
7Checks that the text of 'result-message' is 'Button clicked!'Text content matches expected stringassertEquals("Button clicked!", message.getText())PASS
8Test ends and browser closesBrowser window closes, driver quits-PASS
Failure Scenario
Failing Condition: The button with text 'Click Me' is not found on the page
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath expression is used to find a button by its visible text?
A//button[text()='Click Me']
B//button[@id='Click Me']
C//button[contains(@class, 'Click Me')]
D//button[text()='Submit']
Key Result
Using XPath with text() lets you find elements by their visible text, which is helpful when IDs or classes are not available or dynamic.