Environment Setup
Adding Selenium to Your Project
Reading10 min read
Adding Selenium to Your Project
With Java and Maven installed, adding Selenium is a single pom.xml change — but the dependency choices you make now affect your project's long-term maintainability.
The pom.xml Dependencies
<dependencies>
<!-- Selenium WebDriver -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.20.0</version>
</dependency>
<!-- TestNG test framework -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
<!-- WebDriverManager — handles browser driver binaries automatically -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.8.0</version>
<scope>test</scope>
</dependency>
</dependencies>
WebDriverManager: No More Manual Driver Downloads
Before Selenium 4.6, you had to manually download ChromeDriver and keep it in sync with your Chrome version. WebDriverManager automates this:
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
Selenium 4.6+ includes Selenium Manager which does this automatically — you may not even need WebDriverManager. But it is useful for older setups and customisation.
Your First Driver Instance
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class DriverFactory {
public static WebDriver createChromeDriver() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new"); // remove for debugging
options.addArguments("--window-size=1920,1080");
return new ChromeDriver(options);
}
}
Always run headless in CI. Run headed (remove --headless) when debugging locally.
Always Quit the Driver
WebDriver driver = DriverFactory.createChromeDriver();
try {
driver.get("https://example.com");
// ... test code
} finally {
driver.quit(); // closes browser AND kills the driver process
}
driver.quit() is different from driver.close():
close(): closes the current browser window onlyquit(): closes all windows and terminates the WebDriver session (no memory leak)
Always use quit() in a finally block or @AfterMethod to ensure cleanup even when tests fail.