OpenWindowAction extends AbstractSeleniumAction { @Override protected void execute(SeleniumBrowser browser, TestContext context) { Set<String> windowHandles = browser.getWebDriver().getWindowHandles(); String newWindow = null; String lastWindow = browser.getWebDriver().getWindowHandle(); context.setVariable(SeleniumHeaders.SELENIUM_LAST_WINDOW, lastWindow); if (browser.getWebDriver() instanceof JavascriptExecutor) { ((JavascriptExecutor) browser.getWebDriver()).executeScript("window.open();"); } Set<String> newWindowHandles = browser.getWebDriver().getWindowHandles(); for (String window : newWindowHandles) { if (!windowHandles.contains(window)) { newWindow = window; } } if (!StringUtils.isEmpty(newWindow)) { browser.getWebDriver().switchTo().window(newWindow); log.info("Open window: " + newWindow); context.setVariable(SeleniumHeaders.SELENIUM_ACTIVE_WINDOW, newWindow); context.setVariable(windowName, newWindow); } else { throw new CitrusRuntimeException("Failed to open new window"); } } OpenWindowAction(Builder builder); String getWindowName();  }
@Test public void testOpenWindow() throws Exception { Set<String> windows = new HashSet<>(); windows.add("active_window"); windows.add("new_window"); when(webDriver.getWindowHandles()).thenReturn(Collections.singleton("active_window")).thenReturn(windows); when(webDriver.getWindowHandle()).thenReturn("active_window"); when(webDriver.executeScript(eq("window.open();"))).thenReturn(Collections.emptyList()); OpenWindowAction action = new OpenWindowAction.Builder() .browser(seleniumBrowser) .window("myNewWindow") .build(); action.execute(context); Assert.assertEquals(context.getVariable(SeleniumHeaders.SELENIUM_LAST_WINDOW), "active_window"); Assert.assertEquals(context.getVariable(SeleniumHeaders.SELENIUM_ACTIVE_WINDOW), "new_window"); Assert.assertEquals(context.getVariable("myNewWindow"), "new_window"); verify(locator).window("new_window"); }
@Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = "Failed to open new window") public void testOpenWindowFailed() throws Exception { when(webDriver.getWindowHandles()).thenReturn(Collections.singleton("active_window")); when(webDriver.getWindowHandle()).thenReturn("active_window"); when(webDriver.executeScript(eq("window.open();"))).thenReturn(Collections.emptyList()); OpenWindowAction action = new OpenWindowAction.Builder() .browser(seleniumBrowser) .window("myNewWindow") .build(); action.execute(context); }