0
0
Selenium Javatesting~10 mins

XPath with attributes 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 with an attribute filter, clicks it, and verifies the expected text appears.

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 XPathAttributeTest {
    WebDriver driver;

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

    @Test
    public void testButtonClickByXPathAttribute() {
        driver.get("https://example.com/testpage");
        WebElement button = driver.findElement(By.xpath("//button[@id='submit-btn']"));
        button.click();
        WebElement message = driver.findElement(By.id("result-message"));
        assertEquals("Success", message.getText());
    }

    @AfterEach
    public void tearDown() {
        driver.quit();
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigates to https://example.com/testpagePage loads with a button having id 'submit-btn' and a hidden result message-PASS
3Finds button using XPath //button[@id='submit-btn']Button element located successfullyElement found matches XPath with attribute id='submit-btn'PASS
4Clicks the buttonButton click triggers page update showing result message-PASS
5Finds element with id 'result-message'Result message element is visible with text 'Success'Element text equals 'Success'PASS
6Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: Button with id 'submit-btn' is not found on the page
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath expression is used to find the button in this test?
A//div[@class='submit-btn']
B//button[text()='Submit']
C//button[@id='submit-btn']
D//input[@type='button']
Key Result
Using XPath with attributes lets you precisely find elements by their properties, making tests more reliable and easier to maintain.