Test Overview
This test opens a webpage that opens a new browser window. It switches control to the new window using window handles and verifies the new window's title.
This test opens a webpage that opens a new browser window. It switches control to the new window using window handles and verifies the new window's title.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.Set; import java.util.Iterator; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; public class WindowHandlesTest { WebDriver driver; @Before public void setUp() { driver = new ChromeDriver(); } @Test public void testSwitchToNewWindow() { driver.get("https://example.com/page_with_popup"); // Click button that opens new window driver.findElement(By.id("openWindowBtn")).click(); // Get all window handles Set<String> windowHandles = driver.getWindowHandles(); Iterator<String> iterator = windowHandles.iterator(); String originalWindow = iterator.next(); String newWindow = iterator.next(); // Switch to new window driver.switchTo().window(newWindow); // Verify new window title String expectedTitle = "New Window Title"; String actualTitle = driver.getTitle(); assertEquals(expectedTitle, actualTitle); // Switch back to original window driver.switchTo().window(originalWindow); } @After public void tearDown() { driver.quit(); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com/page_with_popup | Page with a button that opens a new window is loaded | - | PASS |
| 3 | Finds button with id 'openWindowBtn' and clicks it | New browser window opens alongside original window | - | PASS |
| 4 | Calls driver.getWindowHandles() to get all window handles | Two window handles are retrieved: original and new | Verify two window handles exist | PASS |
| 5 | Switches control to the new window using driver.switchTo().window(newWindow) | Browser focus is on the new window | - | PASS |
| 6 | Gets the title of the new window | New window is fully loaded | Assert that title equals 'New Window Title' | PASS |
| 7 | Switches back to original window using driver.switchTo().window(originalWindow) | Browser focus returns to original window | - | PASS |
| 8 | Test ends and browser closes | All browser windows closed | - | PASS |