Test Overview
This test opens a browser, navigates to a sample page, finds a button by its ID, clicks it, and verifies the expected text appears.
This test opens a browser, navigates to a sample page, finds a button by its ID, clicks it, and verifies the expected text appears.
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 FindElementByIdTest { private WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @Test public void testClickButtonById() { driver.get("https://example.com/testpage"); WebElement button = driver.findElement(By.id("submit-btn")); button.click(); WebElement message = driver.findElement(By.id("result-message")); assertEquals("Success!", message.getText()); } @AfterEach public void tearDown() { driver.quit(); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and ChromeDriver is initialized | Browser window opens, ready for commands | — | PASS |
| 2 | Navigate to URL https://example.com/testpage | Browser displays the test page with a button having ID 'submit-btn' | — | PASS |
| 3 | Find element by ID 'submit-btn' | Button element located on the page | Element with ID 'submit-btn' is found | PASS |
| 4 | Click the button element | Button is clicked, page updates to show result message | — | PASS |
| 5 | Find element by ID 'result-message' | Result message element located on the page | Element with ID 'result-message' is found | PASS |
| 6 | Assert that the text of 'result-message' is 'Success!' | Text content of the element is 'Success!' | AssertEquals passes confirming text matches expected | PASS |
| 7 | Close the browser and end test | Browser window closes | — | PASS |
findElement(By.id("submitBtn")) do?findElement locates a single web element on the page.By.id("submitBtn") means it looks for an element with the exact ID "submitBtn".By.id is called with parentheses and a string argument, like By.id("username").By.id must be lowercase 'id', and parentheses are required.WebElement button = driver.findElement(By.id("loginBtn"));
button.click();findElement throws NoSuchElementException immediately.findElement line, so button.click() is never reached.WebElement input = driver.findElement(By.id("email"));
input.sendKeys("test@example.com");
WebElement submit = driver.findElement(By.id("submit"));
submit.click();
Assuming the page has no element with ID "submit".sendKeys works fine.findElement(By.id("submit")) throws NoSuchElementException.Pass the test and this pattern moves unknown