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

Play Extreme ASP.NET Makeover: Testing - Eliminating Repetition from Tests
Sign in to queue

Description

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 https://msdn.microsoft.com/en-us/magazine/dd744751.aspx

Embed

Download

Download this episode

The Discussion

Add Your 2 Cents