Verify page title and URL after navigating to example.com
Preconditions (3)
✅ Expected Result: The page title matches 'Example Domain' and the URL matches 'https://www.example.com/'
import org.openqa.selenium.WebDriver; 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 PageTitleAndUrlTest { private WebDriver driver; @BeforeEach public void setUp() { // Assuming chromedriver is in system PATH driver = new ChromeDriver(); } @Test public void testPageTitleAndUrl() { driver.get("https://www.example.com"); String actualTitle = driver.getTitle(); String actualUrl = driver.getCurrentUrl(); assertEquals("Example Domain", actualTitle, "Page title should be 'Example Domain'"); assertEquals("https://www.example.com/", actualUrl, "URL should be 'https://www.example.com/'"); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
This test class uses JUnit 5 and Selenium WebDriver with ChromeDriver.
setUp() method initializes the ChromeDriver before each test.
testPageTitleAndUrl() navigates to 'https://www.example.com', retrieves the page title and URL, then asserts both match the expected values with clear messages.
tearDown() closes the browser after the test to free resources.
This structure ensures the browser opens fresh for each test and closes properly, following best practices.
Now add data-driven testing with 3 different URLs and their expected titles
getTitle()getCurrentUrl() returns the URL, not the title. The other options are not valid Selenium methods.driver?getCurrentUrl().String url = driver.getCurrentUrl(); is correct syntax.String title = driver.getTitle(); String url = driver.getCurrentUrl(); System.out.println(title); System.out.println(url);
getTitle() returns the page title "Welcome Page" and getCurrentUrl() returns the URL "https://example.com/home".System.out.println(driver.gettitle()); System.out.println(driver.getCurrentUrl);
gettitle() should be getTitle().getCurrentUrl is missing parentheses (), so it is not a valid method call.assertEquals(driver.getTitle(), "Dashboard") correctly checks exact title match.assertTrue(driver.getCurrentUrl().contains("dashboard")) correctly checks URL contains substring "dashboard".Pass the test and this pattern moves unknown