0
0
Selenium Javatesting~10 mins

Creating new windows/tabs in Selenium Java - Test Execution Walkthrough

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

Test Code - JUnit
Selenium Java
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();
        }
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open with no page loaded-PASS
2Navigate to https://example.comBrowser displays Example Domain pagePage title is 'Example Domain'PASS
3Store original window handleOriginal tab handle saved for later-PASS
4Open a new browser tab and switch to itNew tab is active, original tab still open-PASS
5Navigate new tab to https://www.wikipedia.orgNew tab displays Wikipedia homepagePage title is 'Wikipedia'PASS
6Switch back to original tabOriginal tab is active showing Example DomainPage title is 'Example Domain'PASS
7Test ends and browser closesAll browser windows closed-PASS
Failure Scenario
Failing Condition: New tab fails to open or navigation to Wikipedia fails
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test do after opening a new tab?
ASwitches back to the original tab without navigation
BCloses the new tab immediately
CNavigates the new tab to Wikipedia homepage
DRefreshes the original tab
Key Result
Always store the original window handle before opening new tabs or windows so you can switch back reliably during tests.