下面列出了怎么用org.openqa.selenium.interactions.Actions的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public ElementsCollection selectRows(By rowBy) {
this.shouldBe(VISIBLE)
.shouldBe(LOADED)
.shouldBe(ENABLED);
ElementsCollection rows = getRows(rowBy);
WebDriver webDriver = WebDriverRunner.getWebDriver();
Actions action = new Actions(webDriver);
for (SelenideElement row : rows) {
row.shouldNotHave(selectedClass);
Keys controlKey = getControlKey();
action.keyDown(controlKey)
.click(row.getWrappedElement())
.keyUp(controlKey)
.build()
.perform();
}
return rows;
}
/**
* Drag and drop an element on top of other element
* @param targetElement the target element
*/
@Override
@PublicAtsApi
public void dragAndDropTo(
HtmlElement targetElement ) {
new RealHtmlElementState(this).waitToBecomeExisting();
WebElement source = RealHtmlElementLocator.findElement(this);
WebElement target = RealHtmlElementLocator.findElement(targetElement);
Actions actionBuilder = new Actions(webDriver);
Action dragAndDropAction = actionBuilder.clickAndHold(source)
.moveToElement(target, 1, 1)
.release(target)
.build();
dragAndDropAction.perform();
// drops the source element in the middle of the target, which in some cases is not doing drop on the right place
// new Actions( webDriver ).dragAndDrop( source, target ).perform();
}
/**
* Check the check box
*/
@Override
@PublicAtsApi
public void check() {
new MobileElementState(this).waitToBecomeExisting();
try {
WebElement checkboxElement = MobileElementFinder.findElement(appiumDriver, this);
if (!checkboxElement.isSelected()) {
if (appiumDriver instanceof AndroidDriver) {
// checkboxElement.click(); // throwing exception (on Android) with message: Element is not clickable at point (x,y). Other element would receive the click
new Actions(appiumDriver).moveToElement(checkboxElement).click().perform();
} else {
checkboxElement.click();
}
}
} catch (Exception se) {
throw new MobileOperationException(this, "check", se);
}
UiEngineUtilities.sleep();
}
@Test
@Ignore("See if can be run with phantomjs and/or update to geckodriver")
public void testErrorMessageForNonNullAnnotatedComponent() throws InterruptedException {
driver.navigate().to(
"http://localhost:5678/"
+ MBeanFieldGroupRequiredErrorMessage.class.getCanonicalName());
new WebDriverWait(driver, 30).until(VaadinConditions::ajaxCallsCompleted);
WebElement txtField = driver.findElement(By.id("txtStreet"));
Actions toolAct = new Actions(driver);
toolAct.moveToElement(txtField).build().perform();
Thread.sleep(1000);
WebElement toolTipElement = driver.findElement(By.cssSelector(".v-app.v-overlay-container > .v-tooltip > .popupContent .v-errormessage > div > div"));
assertThat(toolTipElement.getText(), is(expectedMessage));
}
@Override
public SelenideElement deselectRow(By rowBy) {
this.shouldBe(VISIBLE)
.shouldBe(ENABLED);
SelenideElement row = getRow(rowBy)
.shouldBe(visible)
.shouldHave(selectedClass);
WebDriver webDriver = WebDriverRunner.getWebDriver();
Actions action = new Actions(webDriver);
Keys controlKey = getControlKey();
action.keyDown(controlKey)
.click(row.getWrappedElement())
.keyUp(controlKey)
.build()
.perform();
return row;
}
@Test
public void replaceComponentAfterRefresh_componentIsReplaced() {
open();
if (hasClientIssue("7587")) {
return;
}
waitPageLoad();
new Actions(getDriver()).sendKeys(Keys.ENTER).build().perform();
List<WebElement> infos = findElements(By.className("info"));
Assert.assertEquals(1, infos.size());
Assert.assertEquals("Clicked", infos.get(0).getText());
open();
waitPageLoad();
new Actions(getDriver()).sendKeys(Keys.ENTER).build().perform();
infos = findElements(By.className("info"));
Assert.assertEquals(2, infos.size());
Assert.assertEquals("Clicked", infos.get(1).getText());
}
private void checkSimpleCtrlBInteractionWorks() {
driver.get(KEY_CLICK_DISPLAY);
new Actions(driver).keyDown(Keys.CONTROL).
sendKeys("b").
keyUp(Keys.CONTROL).
perform();
System.out.println(driver.findElement(By.id("events")).getText());
assertEquals( "only expected 4 events",
4,
driver.findElements(
By.cssSelector("#events p")).size());
}
@Override
protected void configure() {
Multibinder.newSetBinder(binder(), WebDriverEventListener.class);
Multibinder<WebDriverClosedListener> closedListeners = Multibinder
.newSetBinder(binder(), WebDriverClosedListener.class);
closedListeners.addBinding().to(FrameSwitcher.class);
closedListeners.addBinding().to(ProxyCloser.class);
install(new FactoryModuleBuilder()
.implement(ClosingAwareWebDriver.class, ClosingAwareWebDriverWrapper.class)
.build(ClosingAwareWebDriverFactory.class));
bind(WebDriver.class).toProvider(WebDriverProvider.class);
bind(Actions.class).toProvider(ActionsProvider.class);
bind(Capabilities.class).toProvider(CapabilitiesProvider.class);
bind(JavascriptExecutor.class).toProvider(JavascriptExecutorProvider.class);
}
public void subMenu() throws Throwable {
driver = new JavaDriver();
WebElement menu = driver.findElement(By.cssSelector("menu"));
AssertJUnit.assertEquals("A Menu", menu.getText());
new Actions(driver).moveToElement(menu).click().perform();
List<WebElement> menuItems = driver.findElements(By.cssSelector("menu"));
int i = 2;
assertMenuItem(menuItems, i++, "A submenu", "", "83");
/*
* NOTE: Clicking on the menu again to ensure that MenuManager sets the
* state of this menu to closed. Without this call the state of the menu
* remains open and this test or the next test which clicks on the same
* menu and perform any actions or request attributes will fail. This
* behavior is noticed on OSX
*/
new Actions(driver).moveToElement(menu).click().perform();
}
public void chooseCommandTypeInContextMenu(String type) {
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[@class='popupContent']/select[contains(@class,'gwt-ListBox')]")));
WebElement commandTypeElement =
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(
ExpectedConditions.elementToBeClickable(getCommandTypeElementInContextMenu(type)));
commandTypeElement.click();
new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC)
.until(ExpectedConditions.elementToBeSelected(commandTypeElement));
// add timeout to be sure webelement ready to dbClick in some test got exception here
WaitUtils.sleepQuietly(200, TimeUnit.MILLISECONDS);
new Actions(seleniumWebDriver).doubleClick(commandTypeElement).perform();
}
public void checkBoxMenuItemClick() throws Throwable {
driver = new JavaDriver();
WebElement menu = driver.findElement(By.cssSelector("menu"));
AssertJUnit.assertEquals("A Menu", menu.getText());
new Actions(driver).moveToElement(menu).click().perform();
List<WebElement> menuItems = driver.findElements(By.cssSelector("check-box-menu-item"));
int i = menuItems.size();
assertMenuItemClick(menuItems, --i,
"Event source: Another one (an instance of JCheckBoxMenuItem)\n New state: selected\n");
WebElement currRadioButton = menuItems.get(i);
AssertJUnit.assertEquals("true", currRadioButton.getAttribute("selected"));
new Actions(driver).moveToElement(menu).click().perform();
assertMenuItemClick(menuItems, --i,
"Event source: A check box menu item (an instance of JCheckBoxMenuItem)\n New state: selected\n");
currRadioButton = menuItems.get(i);
AssertJUnit.assertEquals("true", currRadioButton.getAttribute("selected"));
}
@Test
public void automateJavaScriptDragAndDropWithOffsetsStep4() {
driver.get("http://web.masteringselenium.com/jsDragAndDropWithHandle.html");
Actions advancedActions = new Actions(driver);
final By destroyableBoxes = By.cssSelector("ul > li > div");
WebElement obliterator = driver.findElement(By.id("obliterate"));
WebElement firstBox = driver.findElement(By.id("one"));
WebElement firstBoxText = driver.findElement(By.cssSelector("#one > span"));
assertThat(driver.findElements(destroyableBoxes).size()).isEqualTo(5);
CalculateOffsetPosition op =
new CalculateOffsetPosition(firstBox, firstBoxText, CursorPosition.CENTER);
advancedActions.moveToElement(firstBox)
.moveByOffset(op.getXOffset(), op.getYOffset())
.clickAndHold()
.moveToElement(obliterator)
.release()
.perform();
assertThat(driver.findElements(destroyableBoxes).size()).isEqualTo(4);
}
@Test
public void homePageShouldWork() throws IOException {
driver.get("http://localhost:" + port);
assertThat(driver.getTitle())
.isEqualTo("Learning Spring Boot: Spring-a-Gram");
String pageContent = driver.getPageSource();
assertThat(pageContent)
.contains("<a href=\"/images/bazinga.png/raw\">");
WebElement element = driver.findElement(
By.cssSelector("a[href*=\"bazinga.png\"]"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
driver.navigate().back();
}
@Test
public void homePageShouldWork() throws IOException {
driver.get("http://localhost:" + port);
takeScreenshot("homePageShouldWork-1");
assertThat(driver.getTitle())
.isEqualTo("Learning Spring Boot: Spring-a-Gram");
String pageContent = driver.getPageSource();
assertThat(pageContent)
.contains("<a href=\"/images/bazinga.png/raw\">");
WebElement element = driver.findElement(
By.cssSelector("a[href*=\"bazinga.png\"]"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
takeScreenshot("homePageShouldWork-2");
driver.navigate().back();
}
@Test
public void internalError_showNotification_clickEsc_refresh() {
clickButton(UPDATE);
clickButton("cause-exception");
Assert.assertTrue("The page should not be immediately refreshed after "
+ "a server-side exception", isMessageUpdated());
Assert.assertTrue(
"'Internal error' notification should be present after "
+ "a server-side exception",
isInternalErrorNotificationPresent());
new Actions(getDriver()).sendKeys(Keys.ESCAPE).build().perform();
try {
waitUntil(driver -> !isMessageUpdated());
} catch (TimeoutException e) {
Assert.fail(
"After internal error, pressing esc-key should refresh the page, "
+ "resetting the state of the UI.");
}
Assert.assertFalse(
"'Internal error' notification should be gone after refreshing",
isInternalErrorNotificationPresent());
}
@Action(object = ObjectType.SELENIUM,
desc = "Move the Browser View to the specified element [<Object>]")
public void moveTo() {
if (elementDisplayed()) {
if (Data != null && Data.matches("(\\d)+,(\\d)+")) {
int x = Integer.valueOf(Data.split(",")[0]);
int y = Integer.valueOf(Data.split(",")[1]);
new Actions(Driver).moveToElement(Element, x, y).build().perform();
} else {
new Actions(Driver).moveToElement(Element).build().perform();
}
Report.updateTestLog(Action, "Viewport moved to" + ObjectName, Status.DONE);
} else {
throw new ElementException(ExceptionType.Element_Not_Visible, ObjectName);
}
}
public PolicyPriorityPage(WebDriver driver) throws IOException {
this.driver = driver;
this.actions = new Actions(driver);
this.uiElementMapper = UIElementMapper.getInstance();
// Check that we're on the right page.
if (!(driver.getCurrentUrl().contains("/policy/priority"))) {
throw new IllegalStateException("This is not the policy priority page.");
}
}
public boolean _press()
{
WebElement webElement = getElement();
if (webElement != null && webElement.getSize().getHeight() > 0 && webElement.getSize().getWidth() > 0)
{
if (getWebDriver() instanceof HasInputDevices)
{
if (isTimed())
getActionProvider().startTimer((DeviceWebDriver) getWebDriver(), this, getExecutionContext());
if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof AppiumDriver)
{
new TouchAction((AppiumDriver) ((DeviceWebDriver) getWebDriver()).getNativeDriver()).press(createPoint(webElement)).perform();
}
else if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof RemoteWebDriver)
{
if (((DeviceWebDriver) getWebDriver()).getNativeDriver() instanceof HasTouchScreen)
new TouchActions(getWebDriver()).clickAndHold(webElement).build().perform();
else
new Actions(getWebDriver()).clickAndHold(webElement).build().perform();
}
return true;
}
}
return false;
}
/**
* Performs the multi-select by {@code Shift} key with check selected items.
*
* <p>Note! Before using this method, one item in project explorer must be selected.
*
* @param clickItemPath is the path to item which will be clicked in format: "Test/src/pom.xml".
* @param selectedItemsPaths is the paths to the each items which should be checked.
*/
public void selectMultiFilesByShiftKeyWithCheckMultiselection(
String clickItemPath, List<String> selectedItemsPaths) {
Actions actions = actionsFactory.createAction(seleniumWebDriver);
actions.keyDown(SHIFT).perform();
waitAndSelectItem(clickItemPath);
waitAllItemsIsSelected(selectedItemsPaths);
actions.keyUp(SHIFT).perform();
}
@Action(object = ObjectType.SELENIUM, desc = "Hover over the [<Object>] element")
public void mouseOverElement() {
if (elementPresent()) {
new Actions(Driver).moveToElement(Element).build().perform();
Report.updateTestLog(Action, "Mouse Over to Element '" + ObjectName,
Status.DONE);
} else {
throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
}
}
@Override
public void sendKeys(CharSequence keysToSend) throws WidgetException {
try {
Actions builder = new Actions(getGUIDriver().getWrappedDriver());
synchronized (InteractiveElement.class) {
getGUIDriver().focus();
builder.sendKeys(getWebElement(), keysToSend).build().perform();
}
} catch (Exception e) {
throw new WidgetException("Error while sending keys", getByLocator(),
e);
}
}
public EditPolicyPage(WebDriver driver) throws IOException {
this.driver = driver;
this.actions = new Actions(driver);
this.uiElementMapper = UIElementMapper.getInstance();
// Check that we're on the right page.
if (!(driver.getCurrentUrl().contains("/policy/edit"))) {
throw new IllegalStateException("This is not the edit policy");
}
}
@Test
public void shouldDrag() {
driver.get("http://guidebook.seleniumacademy.com/DragMe.html");
WebElement dragMe = driver.findElement(By.id("draggable"));
Actions actions = new Actions(driver);
actions.dragAndDropBy(dragMe, 300, 200).perform();
}
@Test
public void shouldDragAndDrop() {
driver.get("http://guidebook.seleniumacademy.com/DragAndDrop.html");
WebElement src = driver.findElement(By.id("draggable"));
WebElement trgt = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(src, trgt).perform();
}
@Test
public void shouldDoubleClickElement() {
driver.get("http://guidebook.seleniumacademy.com/DoubleClick.html");
WebElement dblClick = driver.findElement(By.name("dblClick"));
Actions actions = new Actions(driver);
actions.doubleClick(dblClick).perform();
}
@Test
public void shouldContextClick() {
driver.get("http://guidebook.seleniumacademy.com/ContextClick.html");
WebElement contextMenu = driver.findElement(By.id("div-context"));
Actions actions = new Actions(driver);
actions.contextClick(contextMenu)
.click(driver.findElement(By.name("Item 4")))
.perform();
}
@Override
public void doubleClick() throws WidgetException {
try {
Actions builder = new Actions(getGUIDriver().getWrappedDriver());
synchronized (InteractiveElement.class) {
getGUIDriver().focus();
builder.doubleClick(getWebElement()).build().perform();
}
} catch (Exception e) {
throw new WidgetException("Error while double clicking element",
getByLocator(), e);
}
}
/**
* Drags an element a certain distance and then drops it.
*
* @param element to dragAndDrop
* @param offsetX in pixels from the current location to which the element should be moved, e.g., 70
* @param offsetY in pixels from the current location to which the element should be moved, e.g., -300
*/
public void dragAndDrop(final HtmlElement element, final int offsetX,
final int offsetY) {
TestLogging.logWebStep(
"dragAndDrop " + element.toHTML() + " to offset(x,y): (" + offsetX +
"," + offsetY + ")", false);
element.captureSnapshot("before draging");
new Actions(driver).dragAndDropBy((WebElement) element.getElement(),
offsetX, offsetY).perform();
element.captureSnapshot("after dropping");
}
/**
* Simulate mouse over
*/
@Override
@PublicAtsApi
public void mouseOver() {
new RealHtmlElementState(this).waitToBecomeExisting();
WebElement element = RealHtmlElementLocator.findElement(this);
// 1. option
new Actions(webDriver).moveToElement(element).perform();
// 2. option
// element.sendKeys( "" );
// 3. option
// Mouse mouse = ( ( HasInputDevices ) webDriver ).getMouse();
// mouse.mouseMove( ( ( RemoteWebElement ) element ).getCoordinates() );
// 4. option
// String javaScript = "var evObj = document.createEvent('MouseEvents');"
// + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
// + "arguments[0].dispatchEvent(evObj);";
// JavascriptExecutor js = ( JavascriptExecutor ) webDriver;
// js.executeScript( javaScript, element );
UiEngineUtilities.sleep();
}
/**
* 鼠标双击操作
* @param locator 元素locator
*/
public void click_double(Locator locator)
{
WebElement webElement=findElement(locator);
Actions actions=new Actions(driver);
actions.doubleClick(webElement).perform();
//actions.perform();
}