Tuesday, July 17, 2018

Actions on WebElement in Selenium WebDriver

Actions is an interaction generator in Selenium WebDriver which allow us to operate complicated user interactions on web pages.
You can perform actions such as drag and drop, move, click, double-click, and tick and so on.

Here is an example of a demo of drag and drop, and move on a menu.

package me.simplejavautomation;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class ActionsApiTest {

    private WebDriver driver;
    private String url;

    @Before
    public void setUp() {
        driver = new ChromeDriver();
        url = "http://simplejavautomation.blogspot.com/2018/07/demo-page-for-actions-in-selenium.html";
        // go to the demo page
        driver.get(url);
        // maximize the browser window
        driver.manage().window().maximize();
    }

    @After
    public void tearDown() {
        driver.quit();
    }

    @Test
    public void testDragAndDrop() throws InterruptedException {
        // wait 10 seconds if web element is not present
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement from = driver.findElement(By.id("draggable"));
        WebElement to = driver.findElement(By.id("droppable"));

        Actions builder = new Actions(driver);
        // builder.clickAndHold(from).release(to).build().perform();
        builder.dragAndDrop(from, to).build().perform();
    }

    @Test
    public void testMenuClick() throws InterruptedException {
        // wait 10 seconds if web element is not present
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        WebElement automation = driver.findElement(By.id("automation"));

        Actions builder = new Actions(driver);
        builder.moveToElement(automation).build().perform();

        driver.findElement(By.id("selenium")).click();

        assertEquals("Selenium",
             driver.findElement(By.id("selectedText")).getText());
    }

}

No comments:

Post a Comment