Libraries for Unit Testing MVC5 Controllers

Libraries for Unit Testing MVC5 Controllers

There are various libraries available to help you unit test your controller actions, returned views and models, and action results with MVC. One that I have recently started using is TestStack.FluentMVCTesting. This library allows you to perform actions on your controllers within your unit tests, and then verify, with a fluent syntax, that those actions behaved correctly.

Here are a couple examples: (Most code taken from their GitHub documentation):


[Test]
public void Index_ShouldReturnDefaultView()
{
    _controller.WithCallTo(c => c.Index()).ShouldRenderDefaultView();
}

[Test]
public void Index_ShouldReturnDefaultView_WithExpectedModel(){

var vm = new SomeViewModel();
_controller.WithModelErrors().WithCallTo(c => c.Index(vm))
    .ShouldRenderDefaultView()
    .WithModel(vm);

}

[Test]
public void Index_ReturnsNamedView(){

_controller.WithCallTo(c => c.Index())
    .ShouldRenderView("ViewName");

}

These are just a few simple examples, but this library allows you to test (to name a few things):

  • Action returning a default view
  • Action returning a view with expected model
  • Action returning a named view
  • HTTP Status returned by action
  • JSON Data returned by action

I have found it super useful for unit testing my controllers. I also use it in conjunction with Compare .NET Objects, another useful library which allows you to perform equality checks on your objects using recursion. It’s a fairly robust equality checking library and I have found it especially useful when comparing actual rendered models vs expected models.

One example of why you might do this: Say you’re “newing” up a model in your controller action, setting some properties on it, and then returning it along with your view. In this case your expected unit test model and actual model will not be referentially equal, and so a call to .Equals() will always be false, unless you implement custom overrides of .Equals() on all of your models. This is not only a pain, but might be mixing concerns as well.

In conclusion, these two libraries, TestStack.FluentMVCTesting and Compare .NET Objects, allow you to easily write maintainable, thorough unit tests around your controllers, actions and models in MVC.

Let me know if you use them, and what you think.

By | 2015-01-03T17:25:04+00:00 January 3rd, 2015|Categories: C#, General Technology, MVC, Testing|Tags: , |0 Comments

About the Author:

Leave A Comment