0
0
Selenium Javatesting~10 mins

Why selector mastery prevents fragile tests in Selenium Java - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test opens a login page, finds the username input using a robust CSS selector, enters a username, and verifies the input value. It shows how using a strong selector prevents test failures when page structure changes.

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

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

    @Test
    public void testEnterUsernameWithRobustSelector() {
        driver.get("https://example.com/login");
        // Using a robust CSS selector with id and attribute
        WebElement usernameInput = driver.findElement(By.cssSelector("input#username[type='text']"));
        usernameInput.sendKeys("testuser");
        String enteredText = usernameInput.getAttribute("value");
        assertEquals("testuser", enteredText);
    }

    @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/loginLogin page is loaded with username input field visible-PASS
3Finds username input using CSS selector "input#username[type='text']"Username input element is located on the pageElement found and ready for interactionPASS
4Enters text "testuser" into username inputUsername input field contains text "testuser"-PASS
5Gets the value attribute from username inputRetrieved value is "testuser"Assert that entered text equals "testuser"PASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: Using a fragile selector like a generic tag or index that changes when page layout updates
Execution Trace Quiz - 3 Questions
Test your understanding
Why is the selector "input#username[type='text']" considered robust?
ABecause it uses a unique id and attribute to precisely find the element
BBecause it uses only the tag name which is always stable
CBecause it relies on the element's position in the DOM
DBecause it uses a random class name that changes often
Key Result
Using unique and stable selectors like IDs or specific attributes makes tests less fragile and reduces failures caused by UI changes.