_java
Example
First let's import our requisite classes (for annotations (e.g., org.junit.After
, etc.), driving the browser with Selenium (e.g., org.openqa.selenium.WebDriver
, etc.), and matchers for our assertions (e.g., org.hamcrest.CoreMatchers
, etc.)) and start our class with some setup and teardown methods.
// filename: KeyboardKeys.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.Keys;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
public class KeyboardKeys {
WebDriver driver;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}
@After
public void tearDown() throws Exception {
driver.quit();
}
// ...
Now we can wire up our test.
Let's use an example from the-internet that will display what key has been pressed (link). We'll use the result text that gets displayed to perform our assertion.
// filename: KeyboardKeys.java
// ...
@Test
public void uploadFile() throws Exception {
driver.get("http://the-internet.herokuapp.com/key_presses");
driver.findElement(By.id("target")).sendKeys(Keys.SPACE);
assertThat(driver.findElement(By.id("result")).getText(), is("You entered: SPACE"));
// ...
After visiting the page we find an element that's visible (e.g., the one that contains the example on the page) and send the space key to it (e.g., builder.sendKeys(Keys.SPACE).build().perform()
). Then we grab the resulting text (e.g., driver.findElement(By.id("result")).getText()
) and assert that it says what we expect (e.g., is("You entered: SPACE"));
).
Alternatively, we can also issue a key press without finding the element first.
// filename: KeyboardKeys.java
// ...
Actions builder = new Actions(driver);
builder.sendKeys(Keys.LEFT).build().perform();
assertThat(driver.findElement(By.id("result")).getText(), is("You entered: LEFT"));
}
}
Expected Behavior
When you save this file and run it (e.g. mvn clean test
from the command-line) here is what will happen:
- Open the browser
- Visit the page
- Find the element and send the space key to it
- Find the result text on the page and check to that it's what we expect
- Send the left arrow key to the element that's currently in focus
- Find the result text on the page and check to that it's what we expect
- Close the browser
Summary
If you have a specific element that you want to issue key presses to, then finding the element first is the way to go. But if you don't have a receiving element, or you need to string together multiple key presses, then the Action Builder is what you should use.
Thanks to Roman Isko for contributing the initial Java code for this ti.
Happy Testing!