Test Overview
This test demonstrates the difference between driver.close() and driver.quit() in Selenium Java. It verifies that close() closes the current browser window, while quit() closes all windows and ends the WebDriver session.
This test demonstrates the difference between driver.close() and driver.quit() in Selenium Java. It verifies that close() closes the current browser window, while quit() closes all windows and ends the WebDriver session.
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.*; public class CloseVsQuitTest { WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); driver.get("https://example.com"); } @Test public void testCloseClosesCurrentWindow() { String originalWindow = driver.getWindowHandle(); driver.close(); // After close, driver should throw exception when switching to window Exception exception = assertThrows(org.openqa.selenium.NoSuchWindowException.class, () -> { driver.switchTo().window(originalWindow); }); assertNotNull(exception); } @Test public void testQuitClosesAllWindowsAndEndsSession() { driver.quit(); Exception exception = assertThrows(org.openqa.selenium.NoSuchSessionException.class, () -> { driver.getTitle(); }); assertNotNull(exception); } @AfterEach public void tearDown() { try { driver.quit(); } catch (Exception ignored) { } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and ChromeDriver instance is created | Browser window opens and navigates to https://example.com | - | PASS |
| 2 | testCloseClosesCurrentWindow: driver.close() is called to close current window | Browser window closes, WebDriver session still active | Attempt to switch to closed window throws NoSuchWindowException | PASS |
| 3 | testQuitClosesAllWindowsAndEndsSession: driver.quit() is called to close all windows and end session | All browser windows closed, WebDriver session ended | Calling driver.getTitle() throws NoSuchSessionException | PASS |
| 4 | tearDown method calls driver.quit() to ensure cleanup | No browser windows open, session ended | - | PASS |