#TIL: Advanced Selenium Examples

Last week I went over some basic Selenium, showing how you can write tests that can be run against any browser. Today I’m going to highlight some of the more powerful things you can do with Selenium in your integration tests, from automatically finding page elements to executing arbitrary strings of javascript!

Page Factory

One of the most useful things for selenium testing, particularly if you have complex pages or pages you have more than one test case for, is the concept of the Page Factory. Using a page factory, you can specify an object with a bunch of IWebElement properties, each of them with a special FindsBy attribute:

1
2
3
4
5
6
7
8
public class SignupPage
{
  [FindsBy(How=How.Id, Using="first-name")]
  public IWebElement FirstName { get; set; }
  
  [FindsBy(How=How.ClassName, Using="submit")]
  public IWebElement SubmitButton { get; set; }
}

Once you have an object like this, you can get the IWebDriver to automatically populate it by calling PageFactory.InitElements(driver, pageObject). It will automatically execute the Driver.FindElement calls that match up to the FindsBy attributes specified and populate each of your properties accordingly. Now, instead of copy-pasting “driver.FindElement” every time you need to access an element, you can simply refer to an object’s property.

Actions

Sometimes you need to do some complicated UI interaction that can’t be simulated with a simple call to SendText or Click. For that, we can Actions. Actions represent a chain of events that we’d like the browser to execute in succession. Think, for example, selecting certain items in a multi-selectable select box – we’d need to hold down control and then click on each item we’d like to select. This can be easily done with actions (although your mileage may vary with each driver’s implementation of chained events)

1
2
3
4
5
6
var action = new Actions(driver);
action.Click(selectElement.Options[0])
    .KeyDown(Keys.Control)
    .Click(selectElement.Options[2])
    .KeyUp(Keys.Control)
    .Perform();

This code will do exactly what it says, with an end result of the first and third options in the select element being selected.

JavaScript

By simply casting IWebDriver to an IJavaScriptExecutor interface, we can execute arbitrary strings of javascript with the ExecuteScript method.

1
((IJavaScriptExecutor)driver.ExecuteScript("alert('look, it worked!');");

This may seem somewhat pointless (particularly the example above), but we’ve used this to verify settings on jQuery UI controls, see if there’s any outstanding ajax network calls, and other things that you can only do if you had access to javascript. You can even return IWebElements, strings, and other objects from the code, or execute the script asynchronously.

Comments