Tuesday, March 30, 2010

Warming up Sites Before Running Selenium Tests with NUnit’s SetUpFixture

I’ve been running in to a number of problems where my Selenium tests are timing out when they first run in our automated build environment. Our Selenium test build runs three times a day and sets up the environment from scratch using a distribution package created in another automated build process. [Note: This meets my goal of always testing what you release, not just what you can build.]

The issue with starting from scratch every time is that ASP.NET has to compile the site the first time a Selenium instance spins up. This takes long enough that several tests can fail due to timeouts. My local repave process (hacked together from several PowerShell scripts) hits the site before launching my tests; however, I needed some way to do this within my test process.

NUnit’s SetUpFixture attribute to the rescue!

This handy attribute lets you mark a class to run a one-time setup or teardown for a namespace or for an entire assembly. If you qualify the class with a namespace, then setup/teardown will run once for that namespace only. If you don’t qualify the class with a namespace it will run once for the entire assembly it resides in.

This is awesome.

Using this approach, I can fire up a WebClient instance and hit URLs which will force compilation of the target sites. Here’s how I do it:

using System;
using System.Net;
using NUnit.Framework;
using Telligent.Evolution.Tests.Selenium.Common;

public class AssemblySetupFixture
    public void WarmUpSiteAndControlPanelBeforeTesting()
            var webClient = new WebClient();
            webClient.Proxy = null;
            var requestUrl = http://MyHost/SomeUrl;
            var result = webClient.DownloadString(requestUrl);
            requestUrl += "/ADeeperUrl/";
            result = webClient.DownloadString(requestUrl);
        catch (Exception e)

Note there’s no namespace declared, so this snippet runs once for the assembly it runs in. Yes, the catch block is ugly, but this is my first pass at this and I’ll figure out something smarter to do with Exceptions later.

There are a number of ways I could have skinned this cat, but frankly I’d been wanting to try out this NUnit feature for some time and this gave me a nail to use that hammer on. (Because you can’t get enough bad metaphors in one sentence…)

1 comment:

Dan Hounshell said...

Ha. Frazzled Dad doesn't like to use parens too often, but when he does it's a doozy: "(Because you can’t get enough bad metaphors in one sentence…)" :)

Subscribe (RSS)

The Leadership Journey