Double Click trong Selenium WebDriver

Double Click trong Selenium WebDriver

Để thực hiện hành động double click đối với một element trong Selenium, chúng ta sẽ cần dùng tới Action class. Để thực hiện hành động right-click trong Selenium, chúng ta sẽ sử dụng Actions. Actions class là một thư viện được cung cấp bởi Selenium để xử lý các sự kiện bàn phím và chuột.

I. Code snippet to double click an element

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

Ở đây chúng ta sẽ khởi tạo một đối tượng của Actions class. Sau đó, chúng ta sẽ gọi hàm doubleClick() để thực hiện thao tác này. Chỗ này các bạn nhớ lưu ý phải gọi hàm perform() thì code mới work được nhé.

II. Sample code to double click an element

				
					package webdriver;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Action {
	WebDriver driver;
	String projectPath = System.getProperty("user.dir");
	String osName = System.getProperty("os.name");
	Actions action;
	Alert alert;

	@BeforeClass
	public void beforeClass() {
		System.setProperty("webdriver.chrome.driver", projectPath + "\\browserDrivers\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
		driver.manage().window().maximize();
		action = new Actions(driver);
	}

	public void TC_01_DoubleClick() {
		driver.get("https://demo.guru99.com/test/simple_context_menu.html");
		WebElement btnDoubleClick = driver.findElement(By.xpath("//button[text()='Double-Click Me To See Alert']"));

		action.doubleClick(btnDoubleClick).perform();

		sleepInSecond(3);

		// Switch to alert
		alert = driver.switchTo().alert();

		// Click Ok alert
		alert.accept();

		sleepInSecond(3);
	}

	public void sleepInSecond(int timeout) {
		try {
			Thread.sleep(timeout * 1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@AfterClass
	public void afterClass() {
		driver.quit();
	}
}