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

What would a simple unit test look like confirmation that a specific controller exists if I use Rhino Mocks, NUnit, and ASP.NET MVC 2? I'm trying to bow my head to the concept of TDD, but I can’t figure out what a simple test like “Controller XYZ Exists” would look like. Also, what might a unit test look like to check the result of an action from a view ?

+6
tdd nunit asp.net-mvc-2 rhino-mocks
source share
2 answers

Confirm that the controller exists

The presence of unit tests for its actions is a strong suggestion that the controller exists, which leads us to:

What would a unit test look like? Check the action Result from view

Here is 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 that allow you to make fun of the HttpContext as well as check your routes .

+12
source share

Why do you want to check if the controller exists? What you have to do is check the behavior of the controller. The controller is the code you tested, and you put some waiting on it, and then state whether the expectations are justified or not.

There are many step-by-step instructions on how to do TDD using ASP.NET MVC. You can start, for example, here

http://codebetter.com/blogs/jeffrey.palermo/archive/2008/03/09/this-is-how-asp-net-mvc-controller-actions-should-be-unit-tested.aspx

+3
source share

All Articles