Test Overview
This test opens a new browser tab, switches to it, navigates to a URL, and verifies the page title to confirm the new tab loaded correctly.
This test opens a new browser tab, switches to it, navigates to a URL, and verifies the page title to confirm the new tab loaded correctly.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WindowType; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; public class NewTabTest { WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); } @Test public void testOpenNewTab() { driver.get("https://example.com"); String originalHandle = driver.getWindowHandle(); // Open new tab driver.switchTo().newWindow(WindowType.TAB); driver.get("https://www.wikipedia.org"); // Verify new tab title String title = driver.getTitle(); assertEquals("Wikipedia", title); // Switch back to original tab driver.switchTo().window(originalHandle); assertEquals("Example Domain", driver.getTitle()); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser window is open with no page loaded | — | PASS |
| 2 | Navigate to https://example.com | Browser displays Example Domain page | Page title is 'Example Domain' | PASS |
| 3 | Store original window handle | Original tab handle saved for later | — | PASS |
| 4 | Open a new browser tab and switch to it | New tab is active, original tab still open | — | PASS |
| 5 | Navigate new tab to https://www.wikipedia.org | New tab displays Wikipedia homepage | Page title is 'Wikipedia' | PASS |
| 6 | Switch back to original tab | Original tab is active showing Example Domain | Page title is 'Example Domain' | PASS |
| 7 | Test ends and browser closes | All browser windows closed | — | PASS |
driver.switchTo().newWindow() to open new tabs or windows.WindowType.TAB opens a new tab, which matches driver.switchTo().newWindow(WindowType.TAB).driver.switchTo().newWindow() with a WindowType argument.WindowType.WINDOW.driver.get("https://example.com");
String originalHandle = driver.getWindowHandle();
driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://selenium.dev");
System.out.println(driver.getCurrentUrl());
driver.switchTo().window(originalHandle);
System.out.println(driver.getCurrentUrl());driver.get("https://example.com");
driver.newWindow(WindowType.TAB);
driver.get("https://selenium.dev");newWindow() must be called after driver.switchTo().driver.newWindow() directly, which is incorrect syntax.switchTo().newWindow(WindowType.TAB), navigates, switches back using saved handle, and asserts title.Pass the test and this pattern moves unknown