Subscribe to Sergio Tapia - Lost in the GC.        RSS Feed
-----

Unit Testing - Creating a very sexy helper method.

Icon Leave Comment
You like good looking code right? Who doesn't!

This bit of code I picked up from the excellent book: Pro ASP.Net MVC2.

When you're unit testing, you might do something like this:

using NUnit.Framework

[Test]
public void Product_Catalog_Should_List_All_Products()
{
    var viewModelResult = productsController.List();
    var productCount = viewModelResult.Products.Count;
    Assert.AreEqual(3, productCount);
}



Let's create a little helper method that makes our code a little bit sexier (lord knows I like sexy code):

public static class UnitTestHelpers
{
    public static void ShouldEqual<T>(this T actualValue, T expectedValue)
    {
        Assert.AreEqual(expectedValue, actualValue);
    }
}


BEHOLD! GENERICS!

Now, let's spruce up our old unit test. ;)

using NUnit.Framework

[Test]
public void Product_Catalog_Should_List_All_Products()
{
    var viewModelResult = productsController.List();
    var productCount = viewModelResult.Products.Count;
    productsCount.ShouldEqual(3);
}



Now is that nice or what! :)

Added bonus, Visual Studio's intellisense is fully helping you out while coding.

Posted Image

Enjoy!

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)

About Me

Posted Image


Bienvenidos! I'm a USA ex-pat living in Bolivia for the past 10 years. Web development is my forte with a heavy lean for usability and optimization. I'm fluent in both English and Spanish. I guest write for the popular Python website Python Central. Visit my website.

Categories