0
0
Selenium Javatesting~10 mins

findElement by ID 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 by its ID, 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 FindElementByIdTest {
    private WebDriver driver;

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

    @Test
    public void testClickButtonById() {
        driver.get("https://example.com/testpage");
        WebElement button = driver.findElement(By.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 - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and ChromeDriver is initializedBrowser window opens, ready for commands-PASS
2Navigate to URL https://example.com/testpageBrowser displays the test page with a button having ID 'submit-btn'-PASS
3Find element by ID 'submit-btn'Button element located on the pageElement with ID 'submit-btn' is foundPASS
4Click the button elementButton is clicked, page updates to show result message-PASS
5Find element by ID 'result-message'Result message element located on the pageElement with ID 'result-message' is foundPASS
6Assert that the text of 'result-message' is 'Success!'Text content of the element is 'Success!'AssertEquals passes confirming text matches expectedPASS
7Close the browser and end testBrowser window closes-PASS
Failure Scenario
Failing Condition: Element with ID 'submit-btn' is not found on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What method is used to find the button element in this test?
Adriver.findElement(By.name("submit-btn"))
Bdriver.findElement(By.className("submit-btn"))
Cdriver.findElement(By.id("submit-btn"))
Ddriver.findElement(By.tagName("button"))
Key Result
Always use unique and stable IDs for elements you want to find with findElement(By.id) to ensure reliable and fast element location in Selenium tests.