When testing web applications, itโs common to encounter hidden elements such as dropdown menus or tooltips that only appear on hover. Using Selenium Actions class, we can easily hover a menu item to reveal its sub-menu items. We can also use JavaScriptExecutor in cases where Selenium cannot directly interact with hidden elements.
๐ Why Hover is Important in Selenium?
- Many navigation menus use hover to display sub-menu items.
- Hover actions help you test dynamic menus and tooltips.
- Hidden elements can be revealed using
Actions.moveToElement()with onmouseover.
๐ Example 1 โ Hover Using Selenium Actions Class
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 HoverExample {
public static void main(String[] args) {
// Initialize WebDriver (Chrome)
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// Open URL
driver.get("https://www.example.com"); // Replace with your target URL
// Locate the element to hover
WebElement elementToHover = driver.findElement(By.id("menu")); // Replace with your locator
// Create Actions object
Actions actions = new Actions(driver);
// Perform hover action
actions.moveToElement(elementToHover).perform();
// Optional: wait a bit to observe hover effect
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Close browser
driver.quit();
}
}