Mouseover in Selenium WebDriver

Mouseover in Selenium WebDriver

Hello friends! in this post, we will learn to automate the mouseover over an element using Selenium Webdriver with Java. For performing the mouse hover over an element in Selenium, we make use of the Actions class. The Actions class provided by Selenium Webdriver is used to generate complex user gestures including mouseover, right-click, double click, drag, and drop, etc.

Code snippet to mouseover

Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.moveToElement(element).perform();

Here, we are instantiating an object of Actions class. After that, we pass the WebElement to be mouse hovered as a parameter to the moveToElement() method present in the Actions class. Then, we will call the perform() method to perform the generated action.

Sample code to mouse hover over an element

For the demonstration of the mouseover action, we will be launching a Sample Site for Selenium Learning. Then we will mouse hover over the ‘Submit’ button. This will result in a tooltip generation, asserting that the mouseover action is successfully performed.

package seleniumTutorials;
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 MouseOver {

public static void main(String[] args) throws InterruptedException{
WebDriver driver = new FirefoxDriver();

//Launching sample website
driver.get("#/samplesiteforselenium");
driver.manage().window().maximize();

//Mouseover on submit button
Actions action = new Actions(driver);
WebElement btn = driver.findElement(By.id("idOfButton"));
action.moveToElement(btn).perform();

//Thread.sleep just for user to notice the event
Thread.sleep(3000);

//Closing the driver instance
driver.quit();
}

}

Please write to us if you have any queries and share your views. Also please share this post on social media and don’t forget to check our complete selenium tutorial here.

Selenium Step-by-Step Tutorial

От QA genius

Adblock
detector