TDD a controller with ASP.NET MVC 2, NUnit and Rhino Mocks

asp.net-mvc-2nunitrhino-mockstdd

What would a simple unit test look like to confirm that a certain controller exists if I am using Rhino Mocks, NUnit and ASP.NET MVC 2? I'm trying to wrap my head around the concept of TDD, but I can't see to figure out how a simple test like "Controller XYZ Exists" would look. In addition, what would the unit test look like to test an Action Result off a view?

Best Answer

Confirm that a controller exists

Having unit tests on its actions is a strong suggestion that the controller exists which brings us to:

What would the unit test look like to test an Action Result off a view

Here's an example:

public class HomeController: Controller
{
    private readonly IRepository _repository;
    public HomeController(IRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var customers = _repository.GetCustomers();
        return View(customers);
    }
}

And the corresponding unit test:

[Test]
public void HomeController_Index_Action_Should_Fetch_Customers_From_Repo()
{
   // arrange
   var repositoryStub = MockRepository.GenerateStub<IRepository>();
   var sut = new HomeController(repositoryStub);
   var expectedCustomers = new Customer[0];
   repositoryStub
       .Stub(x => x.GetCustomers())
       .Return(expectedCustomers);

   // act
   var actual = sut.Index();

   // assert
   Assert. IsInstanceOfType(typeof(ViewResult), actual);
   var viewResult = (ViewResult)actual;
   Assert.AreEqual(expectedCustomers, viewResult.ViewData.Model);
}

MVCContrib has some great features allowing you to mock HttpContext and also test your routes.

Related Topic