_java
Example
Let's start by importing 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: RightClick.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class RightClick {
WebDriver driver;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
}
@After
public void tearDown() throws Exception {
driver.quit();
}
// ...
Now we're ready to write our test.
Let's use an example from the-internet that will render a custom context menu when we right-click on a specific area of the page (link).
Clicking the context menu item will trigger a JavaScript alert which will say You selected a context menu
. We'll grab this text and use it to assert that the menu was actually triggered.
// filename: RightClick.java
// ...
@Test
public void rightClickTest() throws InterruptedException {
driver.get("http://the-internet.herokuapp.com/context_menu");
WebElement menu = driver.findElement(By.id("hot-spot"));
Actions action = new Actions(driver);
action.contextClick(menu)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ENTER)
.perform();
Alert alert = driver.switchTo().alert();
assertThat(alert.getText(), is(equalTo("You selected a context menu")));
}
}
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 and right-click the area of the page that renders a custom context menu
- Navigate to the context menu option with keyboard keys
- JavaScript alert appears
- Grab the text of the JavaScript alert
- Assert that the text from the alert is what we expect
- Close the browser
Summary
To learn more about context menus, you can read this write-up from the Tree House blog.
Thanks to Roman Isko for contributing the initial Java code for this tip.
Happy Testing!