Friday, October 15, 2010

ASP.NET MVC Controller Action Unit Test Extension Methods

Testing the ActionResult returned by a controller action can be a PITA. You have to get the view name, check that it's correct, get the model, make sure it’s the right type and then do various asserts against it.

We’ve put together a set of extension methods that make writing controller action tests a breeze. Here’s are some examples:

[Test]
public void Show_should_get_reviews_for_product()
{
    controller.Show(1)
        .ReturnsViewResult()
        .WithModel<Product>()
        .AssertAreSame(productRepository.GetById(1), x => x)
        .AssertAreEqual(2, x => x.Reviews.Count());
}

[Test]
public void New_renders_view()
{
    controller.New(5)
        .ReturnsViewResult()
        .WithModel<Review>()
        .AssertAreSame(product, x => x.Product);
}

[Test]
public void NewWithPost_saves_review()
{
    var review = new Review { Product = new Product { Id = 5 } };
    
    controller.New(review)
        .ReturnsRedirectToRouteResult()
        .ToAction("Submitted")
        .WithRouteValue("Id", "5");

    reviewRepository.AssertWasCalled(x => x.SaveOrUpdate(review));
}

You can grab the latest version of the extension methods here:

http://code.google.com/p/sutekishop/source/browse/trunk/Suteki.Shop/Suteki.Common/TestHelpers/ActionResultExtensions.cs

Happy testing!

Update: Jeremy Skinner tells me that the same or similar extension methods are also available in MvcContrib.

No comments: