How to test ToolTip in Selenium

HOME

 WebElement elementWithTooltip = driver.findElement(By.id("toolTipButton"));

Actions actions = new Actions(driver);
actions.moveToElement(elementWithTooltip).perform();

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement tooltip = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'You hovered over the Button')]")));
  if (expectedTooltipText.equals(actualTooltipText)) {
            System.out.println("Tooltip text is correct!");
        } else {
            System.out.println("Tooltip text is incorrect!");
 }

package com.example;

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.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

public class TooltipTest_Demo {

    static WebDriver driver;
    static String expectedTooltipText = "You hovered over the Button";
    static String actualTooltipText;

    public static void main(String[] args) {

        ChromeOptions options = new ChromeOptions();
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();

        driver.get("https://demoqa.com/tool-tips");

        // Locate the element with the tooltip
        WebElement elementWithTooltip = driver.findElement(By.id("toolTipButton"));

        // Perform hover action using Actions class
        Actions actions = new Actions(driver);
        actions.moveToElement(elementWithTooltip).perform();

        // Wait for the tooltip to be visible
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        WebElement tooltip = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(),'You hovered over the Button')]")));

        // Check the tooltip text
        actualTooltipText = tooltip.getText();
        System.out.println("Actual Tooltip Text: " + actualTooltipText);

        if (expectedTooltipText.equals(actualTooltipText)) {
            System.out.println("Tooltip text is correct!");
        } else {
            System.out.println("Tooltip text is incorrect!");
        }

        driver.quit();
    }

}