_csharp
Example
Let's start by importing our requisite classes for our test framework (e.g., NUnit.Framework
), driving the browser with Selenium (e.g., OpenQA.Selenium
, etc.), and start our class off with some setup and teardown methods.
// filename: RightClick.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
public class RightClick
{
IWebDriver Driver;
[SetUp]
public void SetUp()
{
Driver = new FirefoxDriver();
}
[TearDown]
public void TearDown()
{
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.cs
// ...
[Test]
public void RightClickExample()
{
Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/context_menu");
IWebElement MenuArea = Driver.FindElement(By.Id("hot-spot"));
Actions Builder = new Actions(Driver);
Builder.ContextClick(MenuArea)
.SendKeys(Keys.ArrowDown)
.SendKeys(Keys.ArrowDown)
.SendKeys(Keys.ArrowDown)
.SendKeys(Keys.ArrowDown)
.SendKeys(Keys.ArrowDown)
.SendKeys(Keys.Enter)
.Perform();
IAlert Alert = Driver.SwitchTo().Alert();
Assert.That(Alert.Text.Equals("You selected a context menu"));
}
}
Expected Behavior
When you save this file and run it (e.g., nunit3-console.exe .\RightClick.sln
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 and select it
- 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.
Happy Testing!