Thursday, November 20, 2014

Mouse events

Using Selenium to perform drag-drop, Hover, move to particular coordinate, double click and right click we have Actions class for under "java.lang.Object org.openqa.selenium.interactions.Actions" to perform above actions according o the project needs.

Example 1:-
First we need to create object of Actions class by writing this :-                                    
                                           

          
It ask you to import package of Actions class, if you are using eclipse ide after importing package problem will resolve as it requires the argument of  WebDriver type.
Now that argument needs to be passed because the default constructor of the Actions class has predefined argument in it which is showing error. So to resolve this we need to pass variable of WebDriver type like this:-

WebDriver driver = new FirefoxDriver();

Actions actobj=  new Actions(driver);

Now to work on any element of web page we need to create WebElement of it and pass it to different methods of Actions class.

WebElement actionvariable = driver.findElement(By.xpath("//xpath"));

actobj.moveToElement(actionvariable).build().perform();

here build().perform(); is used because many times events are not there associated with the element, so build().perform() creates an event and performs the action.

Example 2:- 
Moving mouse to particular coordinates in the screen.

We have method  dragAndDropBy(source, xOffset, yOffset), here source is the WebElement of starting position  and xOffset, yOffset are the integer values of the x and y coordinates.
Now to fetch the values of x and y coordinates we need to use get location method

WebElement element = driver.findElement(By.xpath("//xpath"));
element.get location();

It will return the WebElement of Point type, so we need to store it in variable of Point type like this:-
Point p = element.get location();

Now, p.getX() and P.getY(); 
will return integer values for X and Y coordinates that we can pass it in dragAndDropBy(source, xOffset, yOffset) method and perform our desired action.

Example 3:- 
Sometimes we are able to inspect element but at the time of script execution we are not to perform click operation on particular button or link without any error using Selenium, to handle this situation Selenium has click method under Actions class syntax :-

click(webElement):Actions-Actions , we need to pass the WebElement in it. and we will be able to perform click method with Webelement as argument.

So again we need to create WebElement of particular element and then we need to pass it in Click(WebElement) as argument.

So, in this way we can perform task as per the requirements. Below is the image attachment for the different methods available under Actions class.

No comments:

Post a Comment