The Selenium WebDriver's Advanced User Interactions API allows us to perform operations from keyboard events and simple mouse events to complex events such as dragging-and-dropping, holding a key and then performing mouse operations using the Actions
class, and building a complex chain of events exactly like a user doing these manually.
The Actions
class implements the builder pattern to create a composite action containing a group of other actions.
In this recipe, we will use the Actions
class to build a chain of events to select rows in a table.
Let's create a test to select the multiple rows from different positions in a table using the Ctrl key (Command key on a Mac). We can select multiple rows by selecting the first row, then holding the Ctrl key (Command key on a Mac), and then selecting another row and releasing the Ctrl key (Command key on a Mac). This will select the desired rows from the table, as shown in the following code:
@Test public void testRowSelectionUsingControlKey() { List<WebElement> tableRows = driver.findElements(By.xpath("//table[@class='iceDatTbl']/tbody/tr")); //Select second and fourth row from table using Control Key. //Row Index start at 0 Actions builder = new Actions(driver); builder.click(tableRows.get(1)) .keyDown(Keys.CONTROL) .click(tableRows.get(3)) .keyUp(Keys.CONTROL) .build().perform(); //Verify Selected Row table shows two rows selected List<WebElement> rows = driver.findElements(By.xpath("//div[@class='icePnlGrp exampleBox']/table[@class='iceDatTbl']/tbody/tr")); assertEquals(2,rows.size()); }
We need to create an instance of the Actions
class by passing the instance of the driver
class to the constructor in the following way:
Actions builder = new Actions(driver);
We will build a chain of events that we need to perform to select the rows. This will require performing a click()
operation on the first row, then holding the Ctrl key (Command key on Mac) using the keyDown()
operation, clicking on the end row, and then releasing the Ctrl key (Command key on Mac) by calling keyUp()
. The Actions
class provides various methods to perform keyboard and mouse operations:
Actions builder = new Actions(driver); builder.click(tableRows.get(1)).keyDown(Keys.CONTROL) .click(tableRows.get(3)).keyUp(Keys.CONTROL) .build().perform();
We can create a composite action that is ready to be performed by calling the perform()
method of the Actions
class.
The Keys class will represent all non-textual keys on the keyboard, for example, the Ctrl key, the Shift key, the function keys, and so on. In the previous example, we used keyDown(Keys.CONTROL)
to press and hold the Ctrl key (Command key on a Mac) until the next operation was completed.
18.118.142.250