下面列出了org.openqa.selenium.WebDriver.Navigation#org.openqa.selenium.WebDriver.TargetLocator 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void testCloseAllWindowsExceptOneNotMobile()
{
when(webDriverProvider.get()).thenReturn(webDriver);
Set<String> windows = new LinkedHashSet<>(List.of(WINDOW1, WINDOW2));
TargetLocator targetLocator = mock(TargetLocator.class);
when(webDriver.getWindowHandles()).thenReturn(windows);
when(webDriver.switchTo()).thenReturn(targetLocator);
Options options = mock(Options.class);
Window window = mock(Window.class);
when(webDriver.manage()).thenReturn(options);
when(options.window()).thenReturn(window);
when(window.getSize()).thenAnswer(i -> new Dimension(DIMENSION_SIZE, DIMENSION_SIZE));
when(webDriverManager.isAndroid()).thenReturn(false);
windowsActions.closeAllWindowsExceptOne();
verify(webDriver, times(1)).close();
}
@Test
void testSwitchToWindowWithMatchingTitle()
{
@SuppressWarnings("unchecked")
Matcher<String> matcher = mock(Matcher.class);
TargetLocator targetLocator = mock(TargetLocator.class);
when(webDriverProvider.get()).thenReturn(webDriver);
mockWindowHandles(WINDOW3, WINDOW2, WINDOW1);
when(webDriver.switchTo()).thenReturn(targetLocator).thenReturn(targetLocator);
when(webDriver.getTitle()).thenReturn(WINDOW3).thenReturn(WINDOW2).thenReturn(WINDOW1);
when(matcher.matches(WINDOW3)).thenReturn(false);
when(matcher.matches(WINDOW2)).thenReturn(false);
when(matcher.matches(WINDOW1)).thenReturn(true);
InOrder inOrder = Mockito.inOrder(targetLocator, targetLocator);
assertEquals(WINDOW1, windowsActions.switchToWindowWithMatchingTitle(matcher));
inOrder.verify(targetLocator).window(WINDOW3);
inOrder.verify(targetLocator).window(WINDOW2);
inOrder.verify(targetLocator).window(WINDOW1);
}
@Test
void testGetUrlValueOfVideoWithName()
{
when(webDriverProvider.get()).thenReturn(webDriver);
WebElement videoFrame = mock(WebElement.class);
when(baseValidations.assertIfAtLeastNumberOfElementsExist(NUMBER_FOUND_VIDEO_MESSAGE, VIDEO_IFRAME_SEARCH, 1))
.thenReturn(Collections.singletonList(videoFrame));
when(searchActions.findElements(eq(webDriver), any(SearchAttributes.class)))
.thenReturn(Collections.singletonList(mock(WebElement.class)));
when(videoFrame.getAttribute(SRC)).thenReturn(VALUE);
when(softAssert.assertNotNull(THE_SRC_VALUE_WAS_FOUND, VALUE)).thenReturn(Boolean.TRUE);
TargetLocator mockedTargetLocator = mock(TargetLocator.class);
when(webDriver.switchTo()).thenReturn(mockedTargetLocator);
when(mockedTargetLocator.frame(videoFrame)).thenReturn(webDriver);
setVariableSteps.getUrlValueOfVideoWithName(NAME, VARIABLE_SCOPE, URL_VARIABLE);
verify(bddVariableContext).putVariable(VARIABLE_SCOPE, URL_VARIABLE, VALUE);
}
@Test
void testGetUrlValueOfVideoWithNullName()
{
when(webDriverProvider.get()).thenReturn(webDriver);
WebElement videoFrame = mock(WebElement.class);
when(baseValidations.assertIfAtLeastNumberOfElementsExist(NUMBER_FOUND_VIDEO_MESSAGE, VIDEO_IFRAME_SEARCH, 1))
.thenReturn(Collections.singletonList(videoFrame));
when(searchActions.findElements(eq(webDriver), any(SearchAttributes.class)))
.thenReturn(List.of());
TargetLocator mockedTargetLocator = mock(TargetLocator.class);
when(webDriver.switchTo()).thenReturn(mockedTargetLocator);
when(mockedTargetLocator.frame(videoFrame)).thenReturn(webDriver);
setVariableSteps.getUrlValueOfVideoWithName(NAME, VARIABLE_SCOPE, URL_VARIABLE);
verify(softAssert).recordFailedAssertion("A video with the " + NAME + " 'name' was not found");
verifyNoInteractions(bddVariableContext);
}
@Test
void testGetNullUrlValueOfVideoWithName()
{
when(webDriverProvider.get()).thenReturn(webDriver);
WebElement videoFrame = mock(WebElement.class);
when(baseValidations.assertIfAtLeastNumberOfElementsExist(NUMBER_FOUND_VIDEO_MESSAGE, VIDEO_IFRAME_SEARCH, 1))
.thenReturn(Collections.singletonList(videoFrame));
when(searchActions.findElements(eq(webDriver), any(SearchAttributes.class)))
.thenReturn(Collections.singletonList(mock(WebElement.class)));
when(videoFrame.getAttribute(SRC)).thenReturn(null);
when(softAssert.assertNotNull(THE_SRC_VALUE_WAS_FOUND, null)).thenReturn(Boolean.FALSE);
TargetLocator mockedTargetLocator = mock(TargetLocator.class);
when(webDriver.switchTo()).thenReturn(mockedTargetLocator);
when(mockedTargetLocator.frame(videoFrame)).thenReturn(webDriver);
setVariableSteps.getUrlValueOfVideoWithName(NAME, VARIABLE_SCOPE, URL_VARIABLE);
verify(bddVariableContext).putVariable(VARIABLE_SCOPE, URL_VARIABLE, null);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
ClassLoader loader = driver.getClass().getClassLoader();
switch (method.getName()) {
case "findElement":
WebElement element = findElement((By) args[0]);
return Optional.ofNullable(element).map(it -> wrapElement(it, loader)).orElse(null);
case "getCurrentEngine":
return engine;
case "getDelegate":
return driver;
case "switchTo":
TargetLocator switched = (TargetLocator) method.invoke(driver, args);
return wrapTarget(switched, loader);
default:
return method.invoke(driver, args);
}
} catch (Exception ex) {
throw ex.getCause();
}
}
public void windowTitleWithPercentage() throws Throwable {
driver = new JavaDriver();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frame.setTitle("My %Dialog%");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
WebElement element1 = driver.findElement(By.name("click-me"));
String id1 = ((RemoteWebElement) element1).getId();
// driver.switchTo().window("My %25Dialog%25");
TargetLocator switchTo = driver.switchTo();
switchTo.window("My %Dialog%");
WebElement element2 = driver.findElement(By.name("click-me"));
String id2 = ((RemoteWebElement) element2).getId();
AssertJUnit.assertEquals(id1, id2);
}
public HiddenHtmlPrompt( UiDriver uiDriver ) {
super(uiDriver);
HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
Field webClientField = null;
boolean fieldAccessibleState = false;
try {
TargetLocator targetLocator = driver.switchTo();
webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
fieldAccessibleState = webClientField.isAccessible();
webClientField.setAccessible(true);
webClient = (WebClient) webClientField.get(targetLocator.defaultContent());
} catch (Exception e) {
throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
} finally {
if (webClientField != null) {
webClientField.setAccessible(fieldAccessibleState);
}
}
}
public HiddenHtmlAlert( UiDriver uiDriver ) {
super(uiDriver);
HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
Field webClientField = null;
boolean fieldAccessibleState = false;
try {
TargetLocator targetLocator = driver.switchTo();
webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
fieldAccessibleState = webClientField.isAccessible();
webClientField.setAccessible(true);
webClient = (WebClient) webClientField.get(targetLocator.defaultContent());
} catch (Exception e) {
throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
} finally {
if (webClientField != null) {
webClientField.setAccessible(fieldAccessibleState);
}
}
}
public HiddenHtmlConfirm( UiDriver uiDriver ) {
super(uiDriver);
HiddenBrowserDriver browserDriver = (HiddenBrowserDriver) uiDriver;
HtmlUnitDriver driver = (HtmlUnitDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
Field webClientField = null;
boolean fieldAccessibleState = false;
try {
TargetLocator targetLocator = driver.switchTo();
webClientField = targetLocator.getClass().getDeclaringClass().getDeclaredField("webClient");
fieldAccessibleState = webClientField.isAccessible();
webClientField.setAccessible(true);
webClient = (WebClient) webClientField.get(targetLocator.defaultContent());
} catch (Exception e) {
throw new SeleniumOperationException("Error retrieving internal Selenium web client", e);
} finally {
if (webClientField != null) {
webClientField.setAccessible(fieldAccessibleState);
}
}
}
@Test
public void windowEvent() {
String windowName = "Window name";
WebDriver mockedDriver = mock(WebDriver.class);
TargetLocator mockedTargetLocator = mock(TargetLocator.class);
WebDriverEventListener listener = mock(WebDriverEventListener.class);
when(mockedDriver.switchTo()).thenReturn(mockedTargetLocator);
EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener);
testedDriver.switchTo().window(windowName);
InOrder order = Mockito.inOrder(mockedTargetLocator, listener);
order.verify(listener).beforeSwitchToWindow(eq(windowName), any(WebDriver.class));
order.verify(mockedTargetLocator).window(windowName);
order.verify(listener).afterSwitchToWindow(eq(windowName), any(WebDriver.class));
verifyNoMoreInteractions(mockedTargetLocator, listener);
}
@Test
void testSwitchTo()
{
TargetLocator targetLocator = Mockito.mock(TargetLocator.class);
when(wrappedDriver.switchTo()).thenReturn(targetLocator);
assertEquals(targetLocator, delegatingWebDriver.switchTo());
}
@Test
void testBeforeWindowWindowNotExists()
{
WebDriver webDriver = mock(WebDriver.class);
webUiContextListener.afterSwitchToWindow(WINDOW_NAME1, webDriver);
TargetLocator targetLocator = mock(TargetLocator.class);
when(webDriver.switchTo()).thenReturn(targetLocator);
when(webDriver.getWindowHandles()).thenReturn(Set.of(WINDOW_NAME2));
webUiContextListener.beforeSwitchToWindow(WINDOW_NAME2, webDriver);
verify(webUiContext).reset();
verify(targetLocator).window(WINDOW_NAME2);
}
@Test
void testCloseAllWindowsExceptOneMobile()
{
WebDriver webDriver = mock(WebDriver.class);
when(webDriverProvider.get()).thenReturn(webDriver);
when(webDriverManager.isAndroid()).thenReturn(true);
Set<String> windows = new LinkedHashSet<>(List.of(WINDOW1, WINDOW2));
TargetLocator targetLocator = mock(TargetLocator.class);
when(webDriver.getWindowHandles()).thenReturn(windows);
when(webDriver.switchTo()).thenReturn(targetLocator);
Navigation navigation = mock(Navigation.class);
when(webDriver.navigate()).thenReturn(navigation);
windowsActions.closeAllWindowsExceptOne();
verify(navigation, times(2)).back();
}
@Test
void testSwitchToNewWindow()
{
when(webDriverProvider.get()).thenReturn(webDriver);
TargetLocator targetLocator = mock(TargetLocator.class);
mockWindowHandles(WINDOW1, WINDOW2);
when(webDriver.switchTo()).thenReturn(targetLocator);
assertEquals(WINDOW2, windowsActions.switchToNewWindow(WINDOW1));
verify(targetLocator).window(WINDOW2);
}
@Test
void testSwitchToNewWindowNoNewWindow()
{
when(webDriverProvider.get()).thenReturn(webDriver);
TargetLocator targetLocator = mock(TargetLocator.class);
mockWindowHandles(WINDOW1);
assertEquals(WINDOW1, windowsActions.switchToNewWindow(WINDOW1));
Mockito.verifyNoInteractions(targetLocator);
}
@Test
void testSwitchToWindowWithMatchingTitleNoDesiredWindow()
{
@SuppressWarnings("unchecked")
Matcher<String> matcher = mock(Matcher.class);
TargetLocator targetLocator = mock(TargetLocator.class);
when(webDriverProvider.get()).thenReturn(webDriver);
mockWindowHandles(WINDOW3, WINDOW2, WINDOW1);
when(webDriver.switchTo()).thenReturn(targetLocator).thenReturn(targetLocator);
when(webDriver.getTitle()).thenReturn(WINDOW3).thenReturn(WINDOW2).thenReturn(WINDOW1);
when(matcher.matches(WINDOW3)).thenReturn(false);
when(matcher.matches(WINDOW2)).thenReturn(false);
when(matcher.matches(WINDOW1)).thenReturn(false);
InOrder inOrder = Mockito.inOrder(targetLocator, targetLocator, targetLocator);
assertEquals(WINDOW1, windowsActions.switchToWindowWithMatchingTitle(matcher));
inOrder.verify(targetLocator).window(WINDOW3);
inOrder.verify(targetLocator).window(WINDOW2);
inOrder.verify(targetLocator).window(WINDOW1);
String switchMessage = "Switching to a window \"{}\"";
String titleMessage = "Switched to a window with the title: \"{}\"";
assertThat(logger.getLoggingEvents(), is(List.of(info(switchMessage, WINDOW3),
info(titleMessage, WINDOW3),
info(switchMessage, WINDOW2),
info(titleMessage, WINDOW2),
info(switchMessage, WINDOW1),
info(titleMessage, WINDOW1))));
}
@Test
void testSwitchToPreviousWindow()
{
when(webDriverProvider.get()).thenReturn(webDriver);
TargetLocator targetLocator = mock(TargetLocator.class);
when(webDriver.getWindowHandles()).thenReturn(Set.of(WINDOW1));
when(webDriver.switchTo()).thenReturn(targetLocator).thenReturn(targetLocator);
windowsActions.switchToPreviousWindow();
verify(targetLocator).window(WINDOW1);
}
@Test
void testCloseCurrentWindow()
{
String currentWindow = CURRENT_WINDOW_GUID;
String windowToSwitchTo = "{248427e8-e67d-47ba-923f-4051f349f813}";
when(webDriverProvider.get()).thenReturn(driver);
when(driver.getWindowHandle()).thenReturn(currentWindow);
Set<String> windowHandles = new LinkedHashSet<>(List.of(currentWindow, windowToSwitchTo));
when(driver.getWindowHandles()).thenReturn(windowHandles);
TargetLocator mockedTargetLocator = mock(TargetLocator.class);
when(driver.switchTo()).thenReturn(mockedTargetLocator);
pageSteps.closeCurrentWindow();
verify(driver).close();
verify(mockedTargetLocator).window(windowToSwitchTo);
}
@Test(expected = NoSuchFrameException.class)
public void testExceptionHandlingInCaseAFrameIsNotFoundForTheGivenIndex() {
TargetLocator locator = mockTargetLocator();
NoSuchFrameException exception = createSeleniumExceptionOfClass(NoSuchFrameException.class);
doThrow(exception).when(locator).frame(INDEX);
try {
cut.setFocusOnFrame(INDEX);
} finally {
verifyLastEventFiredWasExceptionEventOf(exception);
}
}
@Test(expected = NoSuchFrameException.class)
public void testExceptionHandlingInCaseAFrameIsNotFoundForTheGivenNameOrId() {
TargetLocator locator = mockTargetLocator();
NoSuchFrameException exception = createSeleniumExceptionOfClass(NoSuchFrameException.class);
doThrow(exception).when(locator).frame(NAME_OR_ID);
try {
cut.setFocusOnFrame(NAME_OR_ID);
} finally {
verifyLastEventFiredWasExceptionEventOf(exception);
}
}
@Test(expected = NoSuchWindowException.class)
public void testExceptionHandlingInCaseAWindowIsNotFoundForTheGivenNameOrHandle() {
TargetLocator locator = mockTargetLocator();
NoSuchWindowException exception = createSeleniumExceptionOfClass(NoSuchWindowException.class);
doThrow(exception).when(locator).window(NAME_OR_HANDLE);
try {
cut.setFocusOnWindow(NAME_OR_HANDLE);
} finally {
verifyLastEventFiredWasExceptionEventOf(exception);
}
}
@SuppressWarnings("serial")
private static List<WebElement> getElements(WebDriver d, SearchContext sc, String finder) {
String by = finder.substring(0, finder.indexOf("@")).trim();
if(by.charAt(0)==by.charAt(by.length()-1)) {
if(by.charAt(0)=='"' || by.charAt(0)=='\'') {
by = by.substring(1, by.length()-1);
}
}
String classifier = finder.substring(finder.indexOf("@")+1).trim();
if(classifier.charAt(0)==classifier.charAt(classifier.length()-1)) {
if(classifier.charAt(0)=='"' || classifier.charAt(0)=='\'') {
classifier = classifier.substring(1, classifier.length()-1);
}
}
List< WebElement> el = null;
if(by.equalsIgnoreCase("id")) {
el = By.id(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("name")) {
el = By.name(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("class") || by.equalsIgnoreCase("className")) {
el = By.className(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("tag") || by.equalsIgnoreCase("tagname")) {
el = By.tagName(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("xpath")) {
el = By.xpath(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("cssselector") || by.equalsIgnoreCase("css")) {
el = By.cssSelector(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("text")) {
el = By.xpath("//*[contains(text(), '" + classifier+"']").findElements(sc);
} else if(by.equalsIgnoreCase("linkText")) {
el = By.linkText(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("partialLinkText")) {
el = By.partialLinkText(classifier).findElements(sc);
} else if(by.equalsIgnoreCase("active")) {
el = new ArrayList<WebElement>(){{add(((TargetLocator)d).activeElement());}};
}
return el;
}
@Override
public WebDriver switchTo(TargetLocator targetLocator) {
// This is ugly :(
if (targetLocator instanceof CachingTargetLocator) {
return ((CachingTargetLocator) targetLocator).frame(parent, index);
}
parent.switchTo(targetLocator);
return targetLocator.frame(index);
}
@Override
public WebDriver switchTo(TargetLocator targetLocator) {
// This is ugly :(
if (targetLocator instanceof CachingTargetLocator) {
return ((CachingTargetLocator) targetLocator).frame(parent, nameOrId);
}
parent.switchTo(targetLocator);
return targetLocator.frame(nameOrId);
}
@Override
public WebDriver switchTo(TargetLocator targetLocator) {
// This is ugly :(
if (targetLocator instanceof CachingTargetLocator) {
return ((CachingTargetLocator) targetLocator).frame(parent, frameElement);
}
parent.switchTo(targetLocator);
return targetLocator.frame(frameElement);
}
@Override
public WebDriver switchTo(TargetLocator targetLocator) {
if (windowHandle == null) {
windowHandle = findWindow(targetLocator);
}
return targetLocator.window(windowHandle);
}
private String findWindow(TargetLocator targetLocator) {
for (String windowHandle : targetLocator.defaultContent().getWindowHandles()) {
Browser forWindowHandle = By.id(windowHandle).find(Browser.class, parentContext);
view.setContext(forWindowHandle);
if (view.isLoaded()) {
return windowHandle;
}
}
throw new NoSuchWindowException("No window in driver found which has " + view + " "
+ "currently loaded.");
}
@Override
public WebDriver switchTo(TargetLocator targetLocator) {
if (windowHandle == null) {
windowHandle = findWindow(targetLocator);
}
return targetLocator.window(windowHandle);
}
private String findWindow(TargetLocator targetLocator) {
for (String windowHandle : targetLocator.defaultContent().getWindowHandles()) {
if (targetLocator.window(windowHandle).getTitle().equals(title)) {
return windowHandle;
}
}
throw new NoSuchWindowException("No window in driver found which has title: " + title);
}