ASP.NET MVC – Is There Any Real Value in Unit Testing a Controller?

asp.net-mvccunit testing

I hope this question gives some interesting answers because it's one that's bugged me for a while.

Is there any real value in unit testing a controller in ASP.NET MVC?

What I mean by that is, most of the time, (and I'm no genius), my controller methods are, even at their most complex something like this:

public ActionResult Create(MyModel model)
{
    // start error list
    var errors = new List<string>();

    // check model state based on data annotations
    if(ModelState.IsValid)
    {
        // call a service method
        if(this._myService.CreateNew(model, Request.UserHostAddress, ref errors))
        {
            // all is well, data is saved, 
            // so tell the user they are brilliant
            return View("_Success");
        }
    }

    // add errors to model state
    errors.ForEach(e => ModelState.AddModelError("", e));

    // return view
    return View(model);
}

Most of the heavy-lifting is done by either the MVC pipeline or my service library.

So maybe questions to ask might be:

  • what would be the value of unit testing this method?
  • would it not break on Request.UserHostAddress and ModelState with a NullReferenceException? Should I try to mock these?
  • if I refractor this method into a re-useable "helper" (which I probably should, considering how many times I do it!), would testing that even be worthwhile when all I'm really testing is mostly the "pipeline" which, presumably, has been tested to within an inch of it's life by Microsoft?

I think my point really is, doing the following seems utterly pointless and wrong

[TestMethod]
public void Test_Home_Index()
{
    var controller = new HomeController();
    var expected = "Index";
    var actual = ((ViewResult)controller.Index()).ViewName;
    Assert.AreEqual(expected, actual);
}

Obviously I'm being obtuse with this exaggeratedly pointless example, but does anybody have any wisdom to add here?

Looking forward to it…
Thanks.

Best Answer

Even for something so simple, a unit test will serve multiple purposes

  1. Confidence, what was written conforms to expected output. It may seem trivial to verify that it returns the correct view, but the result is objective evidence that the requirement was met
  2. Regression testing. Should the Create method need to change, you still have a unit test for the expected output. Yes, the output could change along and that results in a brittle test but it still is a check against un-managed change control

For that particular action I'd test for the following

  1. What happens if _myService is null?
  2. What happens if _myService.Create throws an Exception, does it throw specific ones to handle?
  3. Does a successful _myService.Create return the _Success view?
  4. Are errors propagated up to ModelState?

You pointed out checking Request and Model for NullReferenceException and I think the ModelState.IsValid will take care of handling NullReference for Model.

Mocking out the Request allows you to guard against a Null Request which is generally impossible in production I think, but can happen in a Unit Test. In an Integration Test it would allow you to provide different UserHostAddress values (A request is still user input as far as the control is concerned and should be tested accordingly)