0
0
Selenium Javatesting~10 mins

Switching between windows in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, clicks a link that opens a new window, switches to the new window, verifies its title, then switches back to the original window and verifies its title.

Test Code - JUnit 5 with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.jupiter.api.*;
import java.util.Set;

public class WindowSwitchTest {
    WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        driver.get("https://example.com");
    }

    @Test
    public void testSwitchBetweenWindows() {
        String originalWindow = driver.getWindowHandle();

        driver.findElement(By.id("open-new-window")).click();

        Set<String> allWindows = driver.getWindowHandles();
        for (String windowHandle : allWindows) {
            if (!windowHandle.equals(originalWindow)) {
                driver.switchTo().window(windowHandle);
                break;
            }
        }

        Assertions.assertEquals("New Window Title", driver.getTitle());

        driver.close();

        driver.switchTo().window(originalWindow);

        Assertions.assertEquals("Original Window Title", driver.getTitle());
    }

    @AfterEach
    public void tearDown() {
        driver.quit();
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opens the URL https://example.comBrowser shows the original page with title 'Original Window Title' and a button with id 'open-new-window'-PASS
2Find element with id 'open-new-window' and click itA new browser window opens alongside the original window-PASS
3Get all window handles and switch to the new window (not the original)Driver context is now the new window-PASS
4Check the title of the new windowNew window is visible with title 'New Window Title'Assert that title equals 'New Window Title'PASS
5Close the new windowNew window closes, original window remains open-PASS
6Switch back to the original windowDriver context is back to original window-PASS
7Check the title of the original windowOriginal window is visible with title 'Original Window Title'Assert that title equals 'Original Window Title'PASS
Failure Scenario
Failing Condition: The new window does not open or the window handle is not found
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test do immediately after clicking the element with id 'open-new-window'?
AIt switches to the new window using its window handle
BIt closes the original window
CIt refreshes the current page
DIt asserts the title of the original window
Key Result
Always store the original window handle before opening a new window so you can switch back reliably after testing the new window.