driver.close() and driver.quit() in Selenium WebDriver?driver.close() closes only the current active browser window. If multiple windows or tabs are open, the others remain open. driver.quit() closes all browser windows opened by the WebDriver and ends the session, freeing up resources.
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.close();
driver.getTitle();Calling close() on the only open window closes that window, but the WebDriver session remains active. However, since no window is open, calling getTitle() causes a NoSuchWindowException because there is no active window to interact with.
driver.quit() in Selenium Java?driver.quit();
// Which assertion below is valid?After driver.quit(), the WebDriver session ends. Any command like getTitle() throws a NoSuchSessionException. Therefore, asserting that this exception is thrown is the correct way to verify the session is closed.
driver.close()?WebDriver driver = new ChromeDriver(); driver.get("https://example.com"); // Open new tab ((JavascriptExecutor)driver).executeScript("window.open('https://google.com','_blank');"); Set<String> handles = driver.getWindowHandles(); Iterator<String> it = handles.iterator(); String first = it.next(); String second = it.next(); driver.switchTo().window(first); driver.close(); driver.switchTo().window(second);
Calling driver.close() closes the current window (the first one). The driver still holds the handle to the closed window if not switched properly. Trying to switch to the second window without updating the handles or switching context causes NoSuchWindowException.
Using @AfterEach ensures that driver.quit() runs after every test method, regardless of test success or failure. This properly closes all browser windows and ends the WebDriver session, preventing resource leaks.