Extreme ASP.NET Makeover: Testing - Eliminating Repetition from Tests

Embed code for this video

Copy the code above to embed our video on your website/blog.

Close

Video format

Option selected may change based on video formats available and browser capability.

Close

Download

Right click “Save as…”

  • High Quality WMV (PC, Xbox, MCE)
  • MP3 (Audio only)
  • MP4 (iPod, Zune HD)
  • Mid Quality WMV (Lo-band, Mobile)
  • WMV (WMV Video)

Eliminating Repetition from Tests

You'll notice a lot of potential for repetition in the CanLogIntoSite test.

· Every WatiN test will have a URL starting with http://localhost:9999.

· Many tests will require the user to be logged in.

· Multiple tests might want to verify the currently logged in user.

As you can imagine, we'll see similar repetition as we write more tests. Let's apply the principle of Don't Repeat Yourself (DRY) to our WatiN test.

Let's apply the principle of Don't Repeat Yourself (DRY) to our WatiN test.

[Test]
public void CanLogIntoSite() {
    using(var browser = new IE()) {
        browser.GoTo(PageUrl.Default);
        browser.LoginAsAdmin();
        Assert.That(browser.IsLoggedInAs("admin"));
    }
}

 

I've created a PageUrl class that is simply a Uri list for pages in the site. I've also created some extension methods on WatiN's Browser class to script out common actions.

public static void LoginAsAdmin(this Browser browser) {
    if(browser.IsLoggedInAs("admin")) {
        return;
    }
    browser.Link(Find.ByTitle("Login")).Click();
    browser.TextField(Find.ByTitle("Type here your Username")).TypeText("admin");
    browser.TextField(Find.ByTitle("Type here your Password")).TypeText("password");
    browser.Button(Find.ByValue("Login")).Click();
}

public static bool IsLoggedInAs(this Browser browser, string expectedUsername) {
    var username = browser.Link(Find.ByTitle(title => title == "Go to your Profile" || 
        title == "Select your language")).Text;
    return username == expectedUsername;
}

 

Not only am I encouraging re-use with my extension methods, I can more readily ascertain what my CanLogIntoSite test does by using concise, meaningful names for the helper methods. I have also eased my maintenance burden because when I do add IDs to the username/password textboxes and correct the grammar, I have minimized the number of changes I will need to fix my tests.


Other videos from this article

· Of Tightropes and Tests

· Using WatiN

· Eliminating Repetition from Tests

· Acceptance Tests

Read the full article at http://msdn.microsoft.com/en-us/magazine/dd744751.aspx

Tags:

Follow the Discussion

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.