Test Overview
This test opens a webpage, finds the first <h1> tag on the page using findElement(By.tagName), and verifies that the heading text matches the expected value.
This test opens a webpage, finds the first <h1> tag on the page using findElement(By.tagName), and verifies that the heading text matches the expected value.
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 FindElementByTagNameTest { private WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @Test public void testFindH1ByTagName() { driver.get("https://example.com"); WebElement heading = driver.findElement(By.tagName("h1")); String headingText = heading.getText(); assertEquals("Example Domain", headingText); } @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 | Navigate to https://example.com | Browser displays the Example Domain webpage with a visible <h1> heading | — | PASS |
| 3 | Find the first <h1> element using driver.findElement(By.tagName("h1")) | The <h1> element with text 'Example Domain' is located | Verify the <h1> element is found and not null | PASS |
| 4 | Get the text of the <h1> element | Text 'Example Domain' is retrieved from the <h1> element | — | PASS |
| 5 | Assert that the heading text equals 'Example Domain' | The heading text matches the expected string | assertEquals("Example Domain", headingText) | PASS |
| 6 | Close the browser and end the test | Browser window is closed | — | PASS |
findElement(By.tagName("button")) do?findElement returns the first matching element found by the locator.By.tagName("button") looks for elements with the tag <button>.findElement requires a By locator with a string argument for tagName.<div> <h1>Title</h1> <h1>Subtitle</h1> </div>
WebElement header = driver.findElement(By.tagName("h1"));
System.out.println(header.getText());WebElement element = driver.findElement(By.tagName("button"));
System.out.println(element.getText());
NoSuchElementException if no element is found, causing runtime error.findElement(By.tagName()) and then clicks it?Pass the test and this pattern moves unknown