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:

public void Show_should_get_reviews_for_product()
        .AssertAreSame(productRepository.GetById(1), x => x)
        .AssertAreEqual(2, x => x.Reviews.Count());

public void New_renders_view()
        .AssertAreSame(product, x => x.Product);

public void NewWithPost_saves_review()
    var review = new Review { Product = new Product { Id = 5 } };
        .WithRouteValue("Id", "5");

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

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

Happy testing!

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

No comments:

Post a Comment

Note: only a member of this blog may post a comment.