Bird
Raised Fist0
Selenium Javatesting~15 mins

Why selector mastery prevents fragile tests in Selenium Java - Automation Benefits in Action

Choose your learning style10 modes available
Verify login button functionality with robust selector
Preconditions (1)
Step 1: Locate the login button using a robust CSS selector based on id or unique attribute
Step 2: Click the login button
Step 3: Verify that the login form is submitted or the next page is loaded
✅ Expected Result: Login button is clicked successfully and the login process proceeds without errors
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the login button is clickable
Verify the page URL or title changes after clicking login button
Best Practices:
Use By.id or By.cssSelector with stable attributes for locating elements
Avoid using brittle XPath expressions that rely on element position
Use explicit waits to ensure elements are ready before interaction
Organize selectors in a Page Object Model for maintainability
Automated Solution
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.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
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.*;
import java.time.Duration;

public class LoginButtonTest {
    private WebDriver driver;
    private WebDriverWait wait;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        driver.get("https://example.com/login");
    }

    @Test
    public void testLoginButtonClick() {
        // Use robust selector by id
        By loginButtonSelector = By.id("login-button");

        // Wait until login button is clickable
        WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(loginButtonSelector));

        // Click the login button
        loginButton.click();

        // Wait for URL to change or page title to indicate login success
        wait.until(ExpectedConditions.not(ExpectedConditions.urlToBe("https://example.com/login")));

        // Assert URL changed from login page
        String currentUrl = driver.getCurrentUrl();
        assertNotEquals("https://example.com/login", currentUrl, "URL should change after login button click");
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

This test uses Selenium WebDriver with Java to automate clicking the login button on a login page.

We use By.id("login-button") as the selector because IDs are usually unique and stable, making the test less fragile.

We apply an explicit wait with ExpectedConditions.elementToBeClickable to ensure the button is ready before clicking.

After clicking, we wait until the URL changes from the login page URL, indicating the login process proceeded.

Finally, we assert that the URL is different from the login page URL to confirm the click had the expected effect.

Setup and teardown methods initialize and close the browser cleanly.

Common Mistakes - 3 Pitfalls
Using brittle XPath selectors that rely on element position like //div[3]/button
Not using explicit waits before interacting with elements
Hardcoding URLs or page titles without verifying dynamic changes
Bonus Challenge

Now add data-driven testing with 3 different login button selectors to verify robustness

Show Hint

Practice

(1/5)
1. Why is it important to use unique attributes like id or name in Selenium selectors?
easy
A. They are harder to write and maintain.
B. They slow down the test execution significantly.
C. They always cause tests to fail.
D. They make tests more stable and less likely to break when the page changes.

Solution

  1. Step 1: Understand selector uniqueness

    Unique attributes like id or name identify elements clearly without confusion.
  2. Step 2: Impact on test stability

    Using unique selectors reduces the chance tests break when page layout or styles change.
  3. Final Answer:

    They make tests more stable and less likely to break when the page changes. -> Option D
  4. Quick Check:

    Unique selectors = stable tests [OK]
Hint: Pick selectors with unique attributes for stable tests [OK]
Common Mistakes:
  • Choosing selectors based on visible text only
  • Using generic tags like div without attributes
  • Ignoring the importance of uniqueness
2. Which of the following is the correct syntax to locate an element by its id in Selenium Java?
easy
A. driver.findElement(By.id("submitBtn"));
B. driver.findElement(By.name="submitBtn");
C. driver.findElement(By.className("submitBtn"));
D. driver.findElement(By.tag("submitBtn"));

Solution

  1. Step 1: Recall Selenium locator syntax

    The correct method to find by id is By.id("value").
  2. Step 2: Check each option

    driver.findElement(By.id("submitBtn")); uses By.id("submitBtn"), which is correct syntax. Others use incorrect methods or syntax.
  3. Final Answer:

    driver.findElement(By.id("submitBtn")); -> Option A
  4. Quick Check:

    Use By.id("...") for id selectors [OK]
Hint: Use By.id("...") to select by id attribute [OK]
Common Mistakes:
  • Using assignment (=) instead of method parameter syntax
  • Confusing By.name and By.id
  • Using non-existent locator methods like By.tag
3. Given the following code snippet, what will be the output if the element with id loginBtn is not present on the page?
try {
  WebElement button = driver.findElement(By.id("loginBtn"));
  System.out.println("Button found");
} catch (NoSuchElementException e) {
  System.out.println("Button not found");
}
medium
A. Button found
B. Button not found
C. No output
D. Compilation error

Solution

  1. Step 1: Understand findElement behavior

    If the element is missing, findElement throws NoSuchElementException.
  2. Step 2: Analyze try-catch block

    The exception is caught, so the catch block prints "Button not found".
  3. Final Answer:

    Button not found -> Option B
  4. Quick Check:

    Missing element triggers catch block [OK]
Hint: Missing element triggers NoSuchElementException catch [OK]
Common Mistakes:
  • Assuming findElement returns null if not found
  • Ignoring exception handling
  • Confusing findElement with findElements
4. You wrote this selector: driver.findElement(By.xpath("//div[@class='btn']")). Your test breaks when the page adds another div with class btn. How can you fix this fragile selector?
medium
A. Use Thread.sleep() before finding the element.
B. Change the selector to By.tagName("div") to select all divs.
C. Use a more specific attribute like an id or unique data-test attribute.
D. Remove the class condition and select by div only.

Solution

  1. Step 1: Identify fragility cause

    The selector matches multiple elements because class btn is not unique.
  2. Step 2: Improve selector specificity

    Using a unique attribute like id or data-test makes the selector stable and precise.
  3. Final Answer:

    Use a more specific attribute like an id or unique data-test attribute. -> Option C
  4. Quick Check:

    Specific unique attributes prevent fragile selectors [OK]
Hint: Pick unique attributes to avoid multiple matches [OK]
Common Mistakes:
  • Selecting all divs causes more fragility
  • Ignoring selector uniqueness
  • Using waits instead of fixing selectors
5. You have a test that uses this selector:
driver.findElement(By.cssSelector("button.submit-btn"))
After a page update, the class name changes to submit-button. What is the best way to prevent such fragile tests in the future?
hard
A. Ask developers to add a unique data-test attribute and use it in selectors.
B. Use XPath with contains() to match partial class names.
C. Use absolute XPath from the root element to the button.
D. Avoid using selectors and rely on screen coordinates.

Solution

  1. Step 1: Understand fragility cause

    Class names often change due to styling updates, breaking selectors based on them.
  2. Step 2: Use stable attributes for selectors

    Unique data-test attributes are designed for testing and rarely change, making tests stable.
  3. Final Answer:

    Ask developers to add a unique data-test attribute and use it in selectors. -> Option A
  4. Quick Check:

    Stable test attributes prevent fragile selectors [OK]
Hint: Use dedicated test attributes like data-test for stable selectors [OK]
Common Mistakes:
  • Using fragile class names in selectors
  • Using absolute XPath which breaks easily
  • Relying on screen coordinates which are unreliable
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard