findElement by partialLinkText in Selenium Java - Build an Automation Script
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertTrue; public class PartialLinkTextTest { private WebDriver driver; private WebDriverWait wait; @BeforeEach public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); driver.get("https://example.com/homepage"); } @Test public void testNavigateUsingPartialLinkText() { // Locate link by partial link text 'Selenium' WebElement link = wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Selenium"))); link.click(); // Wait for URL to contain 'selenium-automation' wait.until(ExpectedConditions.urlContains("selenium-automation")); // Assert URL contains expected text String currentUrl = driver.getCurrentUrl(); assertTrue(currentUrl.contains("selenium-automation"), "URL should contain 'selenium-automation'"); // Assert page title contains expected text String title = driver.getTitle(); assertTrue(title.contains("Selenium Automation"), "Title should contain 'Selenium Automation'"); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
This test uses Selenium WebDriver with JUnit 5 to automate the manual test case.
Setup: We open Chrome browser and navigate to the homepage URL.
Test: We locate the link using By.partialLinkText("Selenium") which finds any link containing the word 'Selenium'. We wait until the link is clickable, then click it.
We then wait explicitly for the URL to contain 'selenium-automation' to ensure the page has loaded.
Assertions check that the current URL and page title contain the expected text, confirming correct navigation.
Teardown: The browser closes after the test to clean up.
This approach uses explicit waits to avoid timing issues and follows best practices for maintainability and reliability.
Now add data-driven testing with 3 different partial link texts to verify navigation for each.