Test Overview
This test opens a browser, navigates to a sample login page, finds the username input field by its name attribute, enters a username, and verifies the input was successful.
This test opens a browser, navigates to a sample login page, finds the username input field by its name attribute, enters a username, and verifies the input was successful.
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 FindElementByNameTest { private WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @Test public void testFindElementByName() { driver.get("https://example.com/login"); WebElement usernameInput = driver.findElement(By.name("username")); usernameInput.sendKeys("testuser"); assertEquals("testuser", usernameInput.getAttribute("value")); } @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 | Browser navigates to https://example.com/login | Login page is loaded with username input field having name='username' | — | PASS |
| 3 | Find element by name 'username' using driver.findElement(By.name("username")) | Username input field is located on the page | Element found with name attribute 'username' | PASS |
| 4 | Enter text 'testuser' into the username input field | Username input field contains text 'testuser' | — | PASS |
| 5 | Verify the input field's value attribute equals 'testuser' | Username input field value is 'testuser' | assertEquals("testuser", usernameInput.getAttribute("value")) | PASS |
| 6 | Test ends and browser closes | Browser window is closed | — | PASS |
findElement(By.name("username")) do in a test script?findElement(By.name("username")) searches for a single element with the name attribute equal to "username".name attribute.By.name("email").driver.findElement(By.name("email")); is valid and correctly uses the name locator.<input name="search">?
WebElement element = driver.findElement(By.name("search"));
System.out.println(element.getTagName());name="search", which is an input tag.getTagName() returns the tag name of the element, which is "input".WebElement element = driver.findElement(By.name("submitBtn"));
element.click();
Assume the page does not have any element with name="submitBtn".findElement throws NoSuchElementException.click() is called, so click is never reached.findElement(By.name("userEmail")) to locate the element inside it.Pass the test and this pattern moves unknown