Better structured Selenium Tests

Selenium is a fantastic tool developed by ThoughtWorks for automated web acceptance tests.
If you're a web developer and you've never used this tool, go check it out immediately!

How I've been generally Selenium is by using the Selenium IDE Firefox Plugin to record my tests - and then copying the automatically generated C# into my test classes.
This is a really quick and easy approach, however the test code get's REALLY ugly REALLY fast.

Then I saw Erik Doernenburg's excellent presentation on Selenium best practices, and heard a great tip that's so simple and elegant I felt stupid for not thinking about it before.

Create a class for each of your web pages and use static methods to wrap the Selenium code. This allows you to create nice, human readable tests that are also far less brittle.

MainPage.cs (C#)
public class MainPage
    public static void Open()

    public static void SearchFor(string searchString)
      // Ugly brittle code nicely wrapped up
      Selenium.Type("txtSearch", searchString);
    public static int NumberOfSearchResults()
      // This function uses regex to return the 
      // number of results on the page

And then in your unit test class:

MainPageUnitTests.cs (C#)
   public void TestForSearch()
     // Nice readable test logic
     Assert.AreEqual(1, MainPage.NumberOfSearchResults(), 
      "Wrong number of results");

Subscribe via RSS

Back to all blog posts