views:

875

answers:

2

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?

+3  A: 

Why you would like to test if a controller exists ? What you should do is to test the controller behaviour. Your controller it's a code under test and you put some expectation on it and then you assert if the expectations are met or not.

There is many walkthrough on how to do TDD with 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

Thomas Jaskula
I've seen that, but it's wrong. You should never assert more than once per test. In addition, it's more focused on the Repository testing than a simple controller test.
Nissan Fan
One assert per test? That might make sense in some context in a far off galaxy but for Controller tests it makes little sense imho.
Todd Smith
+5  A: 

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.

Darin Dimitrov