Open a web page using Selenium WebDriver
Preconditions (3)
✅ Expected Result: The browser opens and loads the page at 'https://example.com'. The current URL matches exactly 'https://example.com/'.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import static org.junit.jupiter.api.Assertions.assertEquals; public class OpenUrlTest { public static void main(String[] args) { // Set system property for ChromeDriver executable System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { // Open the URL driver.get("https://example.com"); // Verify the current URL String currentUrl = driver.getCurrentUrl(); assertEquals("https://example.com/", currentUrl, "URL should match the expected URL"); System.out.println("Test Passed: URL opened correctly."); } finally { // Close the browser driver.quit(); } } }
This code sets up the ChromeDriver path so Selenium can control the browser. It creates a new Chrome browser instance, then uses driver.get() to open the URL https://example.com. After the page loads, it checks the current URL with driver.getCurrentUrl() and compares it to the expected URL using assertEquals. Finally, it closes the browser with driver.quit() inside a finally block to ensure the browser closes even if the test fails.
This approach is simple and clear, perfect for beginners to understand how to open a URL and verify it using Selenium WebDriver in Java.
Now add data-driven testing to open three different URLs and verify each one
driver.get() method do in Selenium WebDriver?driver.get()driver.get()driver.get(String url).driver.get("https://example.com"); is valid Selenium syntax.WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
String title = driver.getTitle();
System.out.println(title);WebDriver driver = new ChromeDriver();
driver.get("https://example.com")
System.out.println(driver.getTitle());driver.get("https://example.com") is missing a semicolon at the end.contains("Example") checks if the title includes the word anywhere.Pass the test and this pattern moves unknown