Bird
Raised Fist0
Selenium Javatesting~15 mins

Mouse hover (moveToElement) in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Verify mouse hover displays submenu
Preconditions (2)
Step 1: Locate the main menu item with text 'Services'
Step 2: Move the mouse pointer over the 'Services' menu item
Step 3: Observe if the submenu appears below the 'Services' menu
✅ Expected Result: The submenu under 'Services' is displayed when mouse hovers over the main menu item
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify submenu element is displayed after mouse hover
Best Practices:
Use Actions class for mouse hover (moveToElement)
Use explicit waits to wait for submenu visibility
Use meaningful locators like By.linkText or By.cssSelector
Avoid Thread.sleep; use WebDriverWait instead
Automated Solution
Selenium Java
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;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import org.junit.Assert;

public class MouseHoverTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

            // Locate the main menu item 'Services'
            WebElement servicesMenu = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Services")));

            // Perform mouse hover using Actions
            Actions actions = new Actions(driver);
            actions.moveToElement(servicesMenu).perform();

            // Wait for submenu to be visible
            WebElement submenu = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("ul.submenu")));

            // Assert submenu is displayed
            Assert.assertTrue("Submenu should be visible after hover", submenu.isDisplayed());

            System.out.println("Test Passed: Submenu displayed on mouse hover.");
        } finally {
            driver.quit();
        }
    }
}

This code opens the website and waits for the 'Services' menu item to be visible. It uses the Actions class to move the mouse pointer over the 'Services' menu. Then it waits explicitly for the submenu to appear using WebDriverWait and ExpectedConditions.visibilityOfElementLocated. Finally, it asserts that the submenu is displayed. The try-finally block ensures the browser closes after the test.

Using explicit waits avoids flaky tests and Actions.moveToElement is the correct way to simulate mouse hover in Selenium.

Common Mistakes - 3 Pitfalls
Using Thread.sleep instead of explicit waits
Using incorrect locator for submenu
Not using Actions class for mouse hover
Bonus Challenge

Now add data-driven testing to hover over three different main menu items and verify their submenus appear.

Show Hint

Practice

(1/5)
1. What is the primary purpose of using moveToElement() in Selenium WebDriver?
easy
A. To scroll the page down
B. To click on a web element
C. To enter text into a text box
D. To simulate mouse hover over a web element

Solution

  1. Step 1: Understand the function of moveToElement()

    The moveToElement() method is used to move the mouse pointer over a specific web element, simulating a hover action.
  2. Step 2: Compare with other actions

    Clicking, scrolling, and typing are done by other methods like click(), scrollTo(), and sendKeys(). So, moveToElement() is specifically for hover.
  3. Final Answer:

    To simulate mouse hover over a web element -> Option D
  4. Quick Check:

    moveToElement() = mouse hover [OK]
Hint: moveToElement() always means mouse hover action [OK]
Common Mistakes:
  • Confusing moveToElement() with click()
  • Using moveToElement() to enter text
  • Thinking moveToElement() scrolls the page
2. Which of the following is the correct syntax to perform a mouse hover on a WebElement named menu using Selenium Actions in Java?
easy
A. driver.moveToElement(menu).hover();
B. Actions.moveToElement(menu).perform();
C. new Actions(driver).moveToElement(menu).perform();
D. Actions(driver).hover(menu).perform();

Solution

  1. Step 1: Recall the Actions class usage

    In Selenium Java, you create an Actions object with new Actions(driver), then chain moveToElement(element) and finish with perform().
  2. Step 2: Check each option's syntax

    new Actions(driver).moveToElement(menu).perform(); correctly creates the Actions object and calls the methods. Options B, C, and D have incorrect method calls or missing object creation.
  3. Final Answer:

    new Actions(driver).moveToElement(menu).perform(); -> Option C
  4. Quick Check:

    Actions object + moveToElement + perform() = correct syntax [OK]
Hint: Always create Actions object before moveToElement() [OK]
Common Mistakes:
  • Calling moveToElement() without Actions object
  • Using driver.moveToElement() which is invalid
  • Forgetting to call perform() at the end
3. Consider the following code snippet:
WebElement menu = driver.findElement(By.id("menu"));
Actions actions = new Actions(driver);
actions.moveToElement(menu).perform();
String tooltip = driver.findElement(By.id("tooltip")).getText();
System.out.println(tooltip);

What will be printed if the tooltip appears only after mouse hover?
medium
A. Empty string is printed
B. The tooltip text is printed
C. NoSuchElementException is thrown
D. StaleElementReferenceException is thrown

Solution

  1. Step 1: Understand the hover effect

    The moveToElement(menu).perform() simulates mouse hover on the menu element, which triggers the tooltip to appear.
  2. Step 2: Check tooltip retrieval

    After hover, the code finds the tooltip element by id and gets its text. Since the tooltip appears on hover, the text will be present and printed.
  3. Final Answer:

    The tooltip text is printed -> Option B
  4. Quick Check:

    Hover triggers tooltip, so text prints [OK]
Hint: Hover first, then get tooltip text to see it [OK]
Common Mistakes:
  • Assuming tooltip is present before hover
  • Not calling perform() after moveToElement()
  • Expecting exceptions without missing elements
4. You wrote this code to hover over an element:
Actions actions = new Actions(driver);
actions.moveToElement(menu);

But the hover effect does not happen. What is the likely mistake?
medium
A. Missing perform() call after moveToElement()
B. Incorrect locator for menu element
C. Actions class cannot perform hover
D. Need to use click() instead of moveToElement()

Solution

  1. Step 1: Check method chaining in Actions

    Actions methods like moveToElement() build the action but do not execute it until perform() is called.
  2. Step 2: Identify missing perform()

    The code misses perform(), so the hover action is never executed.
  3. Final Answer:

    Missing perform() call after moveToElement() -> Option A
  4. Quick Check:

    Always end Actions with perform() [OK]
Hint: Always call perform() to execute Actions chain [OK]
Common Mistakes:
  • Forgetting perform() after moveToElement()
  • Assuming moveToElement() runs immediately
  • Using click() when hover is needed
5. You want to hover over a menu item and then click a submenu item that appears only after hover. Which is the correct way to do this in Selenium Java?
hard
A. new Actions(driver).moveToElement(menu).click(submenu).perform();
B. menu.click(); submenu.click();
C. new Actions(driver).click(menu).click(submenu).perform();
D. driver.findElement(By.id("submenu")).click();

Solution

  1. Step 1: Understand submenu visibility

    The submenu appears only after hovering over the menu, so we must hover first to reveal it.
  2. Step 2: Use Actions to hover and click

    new Actions(driver).moveToElement(menu).click(submenu).perform(); chains moveToElement(menu) to hover, then click(submenu) to click the submenu, and finally perform() to execute both actions in order.
  3. Step 3: Why other options fail

    menu.click(); submenu.click(); clicks menu without hover, so submenu may not appear. new Actions(driver).click(menu).click(submenu).perform(); clicks menu instead of hover. driver.findElement(By.id("submenu")).click(); clicks submenu directly without hover, likely causing failure.
  4. Final Answer:

    new Actions(driver).moveToElement(menu).click(submenu).perform(); -> Option A
  5. Quick Check:

    Hover then click submenu with Actions chain [OK]
Hint: Chain hover and click in Actions, then perform() [OK]
Common Mistakes:
  • Clicking submenu before hover
  • Using click() on menu instead of hover
  • Not chaining actions before perform()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard