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.
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.
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(); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens the URL https://example.com | Browser shows the original page with title 'Original Window Title' and a button with id 'open-new-window' | - | PASS |
| 2 | Find element with id 'open-new-window' and click it | A new browser window opens alongside the original window | - | PASS |
| 3 | Get all window handles and switch to the new window (not the original) | Driver context is now the new window | - | PASS |
| 4 | Check the title of the new window | New window is visible with title 'New Window Title' | Assert that title equals 'New Window Title' | PASS |
| 5 | Close the new window | New window closes, original window remains open | - | PASS |
| 6 | Switch back to the original window | Driver context is back to original window | - | PASS |
| 7 | Check the title of the original window | Original window is visible with title 'Original Window Title' | Assert that title equals 'Original Window Title' | PASS |