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.
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.
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(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com/login | Login page is loaded with username input field visible | - | PASS |
| 3 | Finds username input using CSS selector "input#username[type='text']" | Username input element is located on the page | Element found and ready for interaction | PASS |
| 4 | Enters text "testuser" into username input | Username input field contains text "testuser" | - | PASS |
| 5 | Gets the value attribute from username input | Retrieved value is "testuser" | Assert that entered text equals "testuser" | PASS |
| 6 | Test ends and browser closes | Browser window is closed | - | PASS |