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:
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.