0
0
Selenium Javatesting~10 mins

findElement by cssSelector in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page, finds a button using a CSS selector, clicks it, and verifies the button's text changes as expected.

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

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

    @Test
    public void testFindElementByCssSelector() {
        driver.get("https://example.com/buttonpage");
        WebElement button = driver.findElement(By.cssSelector("button#submit-btn.primary"));
        button.click();
        String buttonText = button.getText();
        assertEquals("Submitted", buttonText);
    }

    @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
2Navigate to URL https://example.com/buttonpageBrowser displays the page with a button having id 'submit-btn' and class 'primary'-PASS
3Find element using CSS selector 'button#submit-btn.primary'Button element located on the pageElement is found and is a button with correct id and classPASS
4Click the found button elementButton is clicked, triggering page or element update-PASS
5Get text of the button after clickButton text is now 'Submitted'Assert that button text equals 'Submitted'PASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: The CSS selector does not match any element on the page
Execution Trace Quiz - 3 Questions
Test your understanding
What does the CSS selector 'button#submit-btn.primary' select?
AA button element with id 'submit-btn' and class 'primary'
BAny element with id 'submit-btn' or class 'primary'
CAny button element with class 'submit-btn' and id 'primary'
DA div element with id 'submit-btn' and class 'primary'
Key Result
Use precise CSS selectors combining tag, id, and class to reliably find elements. Always assert expected changes after interactions.