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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With