Test Overview
This test opens a web page, finds a link by its visible text using Selenium's findElement(By.linkText()) method, clicks the link, and verifies that the navigation was successful by checking the page title.
This test opens a web page, finds a link by its visible text using Selenium's findElement(By.linkText()) method, clicks the link, and verifies that the navigation was successful by checking the page title.
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 LinkTextTest { private WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @Test public void testFindElementByLinkText() { driver.get("https://example.com"); WebElement link = driver.findElement(By.linkText("More information...")); link.click(); String expectedTitle = "IANA — IANA-managed Reserved Domains"; assertEquals(expectedTitle, driver.getTitle()); } @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 homepage with a link labeled 'More information...' | — | PASS |
| 3 | Find the link element by visible link text 'More information...' | Link element is located on the page | Verify element is found without exception | PASS |
| 4 | Click the found link element | Browser navigates to the linked page | — | PASS |
| 5 | Check the page title matches 'IANA — IANA-managed Reserved Domains' | Browser shows the IANA reserved domains page | Assert that actual title equals expected title | PASS |
| 6 | Close the browser and end the test | Browser window is closed | — | PASS |
driver.findElement(By.linkText("Home")) do in Selenium Java?findElement(By.linkText("Home")) searches for a link whose visible text exactly matches "Home".partialLinkText).findElement(By.linkText("Contact Us")) uses double quotes around the string and parentheses correctly.WebElement link = driver.findElement(By.linkText("About"));
System.out.println(link.getText());link.getText() returns the visible text of the link, which is "About".driver.findElement(By.linkText("Login"));By.linkText requires the visible text to match exactly, including spaces.linkText requires exact text, so you must try both versions separately.Pass the test and this pattern moves unknown