UI-testing (EPiServer): improving the test(s)

The code we ended up with in the previous post works but it’s hardly optimal.

There are some tasks that are performed in each and every UI test. For instance, before the test start up the browser and maximize it and after the test close the browser. If we put this common tasks in a base class we end up with this

public class UiTestBase
{
    protected IWebDriver Driver;
    protected const string BaseUrl = "http://alloy.demo.episerver.com";

    [SetUp]
    public void Before()
    {
        Driver = new FirefoxDriver();
        Driver.Manage().Window.Maximize();
    }

    [TearDown]
    public void After()
    {
        Driver.Quit();
    }
}

The test itself now looks like this

[Test]
public class HeaderTest : UiTestBase
{
    public void Alloy_Meet_should_be_marked_in_header_when_browsing_Alloy_Meet_page()
    {
        Driver.Navigate().GoToUrl(BaseUrl + "/Alloy-Meet/");
        var activeLinkText = driver.FindElement(By.CssSelector("ul.nav li.active")).Text;
        Assert.That(activeLinkText, Is.EqualTo("Alloy Meet"));
    }
}

Not a whole load has changed compared to the previous version but we now have a common base that we can use for all out UI-tests. If we were to add another (very) similar test that simply checks that another page is marked in the header the test would look like this

[Test]
public void About_us_should_be_marked_in_header_when_browsing_About_us_page()
{
    Driver.Navigate().GoToUrl(BaseUrl + "/About-us/");
    var activeLinkText = driver.FindElement(By.CssSelector("ul.nav li.active")).Text;
    Assert.That(activeLinkText, Is.EqualTo("About us"));
}

As you can tell we have some duplication between the tests to let’s refactor a bit

public class HeaderTest : UiTestBase
{
    private string GetActiveLinkText()
    {
        return Driver.FindElement(By.CssSelector("ul.nav li.active")).Text;
    }

    [Test]
    public void Alloy_Meet_should_be_marked_in_header_when_browsing_Alloy_Meet_page()
    {
        Driver.Navigate().GoToUrl(BaseUrl + "/Alloy-Meet/");
        Assert.That(GetActiveLinkText(), Is.EqualTo("Alloy Meet"));
    }

    [Test]
    public void About_us_should_be_marked_in_header_when_browsing_About_us_page()
    {
        Driver.Navigate().GoToUrl(BaseUrl + "/About-us/");
        Assert.That(GetActiveLinkText(), Is.EqualTo("About us"));
    }
}
  • Per Magne Skuseth

    Sweet :-) About how much time does it take to run a few tests?

    • http://www.popkram.com Stefan Forsberg

      The next post will address just that subject =)