0
0
Selenium Javatesting~10 mins

Closing browser (close vs quit) in Selenium Java - Test Execution Compared

Choose your learning style9 modes available
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.

Test Code - JUnit 5 with Selenium WebDriver
Selenium Java
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) {
        }
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test starts and ChromeDriver instance is createdBrowser window opens and navigates to https://example.com-PASS
2testCloseClosesCurrentWindow: driver.close() is called to close current windowBrowser window closes, WebDriver session still activeAttempt to switch to closed window throws NoSuchWindowExceptionPASS
3testQuitClosesAllWindowsAndEndsSession: driver.quit() is called to close all windows and end sessionAll browser windows closed, WebDriver session endedCalling driver.getTitle() throws NoSuchSessionExceptionPASS
4tearDown method calls driver.quit() to ensure cleanupNo browser windows open, session ended-PASS
Failure Scenario
Failing Condition: If driver.close() does not close the current window or driver.quit() does not end the session
Execution Trace Quiz - 3 Questions
Test your understanding
What does driver.close() do in Selenium WebDriver?
ACloses the current browser window
BCloses all browser windows and ends the session
CMinimizes the browser window
DRefreshes the current page
Key Result
Always use driver.quit() in cleanup to close all browser windows and properly end the WebDriver session, preventing resource leaks.