Skip to main content

_csharp

Example

First let's include 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: KeyboardKeys.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;

public class KeyboardKeys
{
IWebDriver Driver;

[SetUp]
public void SetUp()
{
Driver = new FirefoxDriver();
}

[TearDown]
public void TearDown()
{
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 on the page to perform our assertion.

// filename: KeyboardKeys.cs
// ...
[Test]
public void KeyboardKeysExample()
{
Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/key_presses");

Driver.FindElement(By.Id("target")).SendKeys(Keys.Space);
Assert.That(Driver.FindElement(By.Id("result")).Text.Equals("You entered: SPACE"));
// ...

After visiting the page we find a visible element (e.g., the primary content of the page) and send the space key to it (e.g., .SendKeys(Keys.SPACE)). Then we grab the resulting text (e.g., Driver.FindElement(By.Id("result")).Text) and assert that it says what we expect (e.g., .Equals("You entered: SPACE").

Alternatively, we can issue a key press without finding the element by using the Selenium Action Builder.

// filename: KeyboardKeys.cs
// ...
Actions Builder = new Actions(Driver);
Builder.SendKeys(Keys.Left).Build().Perform();
Assert.That(Driver.FindElement(By.Id("result")).Text.Equals("You entered: LEFT"));
}
}

Expected Behavior

When you save this file and run it (e.g. nunit3-console.exe .\KeyboardKeys.sln 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 asset 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 assert 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. 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.