0
0
Selenium Javatesting~10 mins

findElement by xpath in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a browser, navigates to a sample page, finds a button using an XPath locator, 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 FindElementByXPathTest {
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        // Set the path to chromedriver executable if necessary
        // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        driver = new ChromeDriver();
    }

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

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            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 message div-PASS
3Finds button element using XPath //button[@id='submit-btn']Button element located on the pageElement is found and not nullPASS
4Clicks the button elementButton click triggers message display-PASS
5Finds message element using XPath //div[@id='message']Message element is visible with text 'Success'Element text equals 'Success'PASS
6Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: The XPath locator does not find the button element because the id is incorrect or element is missing
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test do after opening the browser?
AClicks a button immediately
BNavigates to the test page URL
CCloses the browser
DFinds the message element first
Key Result
Use clear and specific XPath locators to find elements reliably. Always verify the element exists before interacting and assert expected outcomes to confirm test success.