2

How to perform a mouse hover functionality using Selenium Webdriver?

Test Case is like say, open Yahoo site and there is link (Mail) beside Sign-In. Upon mouse hover it will show a tooltip.

When i try the below code, it is not mouse hovering the exact location, rather it hovers somewhere else. Where i am going wrong?

And also let me know, how to capture the Tooltip?

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class Sample 
{
    public static void main(String[] args) 
    {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.yahoo.com");

        driver.manage().window().maximize();

        try 
                {
            Thread.sleep(5000);
        } catch (InterruptedException e)
                {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        WebElement lMail=driver.findElement(By.xpath("//*[@title='Mail']"));

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


    }

}
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Uday
  • 1,433
  • 10
  • 36
  • 57
  • The code looks sane, where are you seeing it hover? – Ardesco Feb 04 '13 at 20:49
  • 1
    I agree with Ardesco, the code looks correct. The only difference I see between yours and what I use is that I don't call `build()` before `perform()`. So my final call looks like this: `new Actions(driver).moveToElement(element).perform();` – Falkenfighter Feb 04 '13 at 22:23

3 Answers3

5
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
Code Enthusiastic
  • 2,827
  • 5
  • 25
  • 39
GirishB
  • 524
  • 1
  • 3
  • 9
1

Try this code:

//Assume driver initialized properly.
WebElement element = driver.findElement(By.id("Element id"));
Locatable hoverItem = (Locatable) element;
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseMove(hoverItem.getCoordinates());
Manigandan
  • 5,004
  • 1
  • 28
  • 47
  • I see some strange behavior here. When i ran the same code in Win XP machine, it is mouse hover on the object, but where as in Win 7, it mouse hover in a different location. In both the above codes, it just mouse hover on the link and after the cursor is moving away(pointing in some different random location). Why is that? Can anybody help here? – Uday Feb 05 '13 at 08:01
  • While running in the XP machine you able to see the `tooltip` text (in your case `Mail`) in visually? – Manigandan Feb 05 '13 at 09:11
0

I have used similar code and it works for me. I have also used the following at a few places: browser.executeScript("jQuery('mycss-selector').mouseover();") You will have to use css-selector, instead of xpath.

Sridevi Yedidha
  • 1,183
  • 1
  • 12
  • 13