Thursday, February 17, 2011

MVC Test Controller Builder and NSubstitute

If you are a web developer using ASP.NET MVC and Unit Test by NSubstitute, this blog is what you are looking for. I am sure there is at least one time you have problem writing unit test for controller but need to mock HttpContext. Whoever used MVCContrib would see that there is a class called TestControllerBuilder to help testing controller easily. However, this helper class is a part of RhinoMock or Moq to mock test objects. So if you want to use NSubstitute to mock objects, you cannot setup HttpContext. Actually you can use RhinoMock or Moq with NSubstitute but I think nobody does that. Using 2 mock frameworks in 1 test method is a little odd. To create mock object for HttpContext with NSubstitute, I decide to implement this helper class based on TestControllerBuilder of MvcContrib. Beside NSubstitute, this helper has a few APIs to mock HtmlHelper if you want to test HtmlHelper extension methods.

Below is the code sample:
[TestMethod]
public void Can_Export_Event_To_Add_To_Yahoo_Calendars()
{
  // Arrange
  EventController _controller = new EventController
  {
      ServiceFactory = Substitute.For<IServiceFactory>()
  };

  var builder = MvcTestControllerBuilder.GetDefaultBuilder();
  builder.InitializeController(_controller);
  builder.HttpContext.Request.Url.Returns(new Uri("http://domain.com/Event/Export"));

  Event evt = SetupEventData();

  // Act
  var result = _controller.Export(Guid.NewGuid(), evt.StartDate, "Yahoo");

  // Assert
  Assert.IsTrue(result is RedirectResult);
}
Source code: Download under WPFPL Updated: Fix the download link

1 comments:

John said...

This was exactly what I was looking for. Thank you!

Post a Comment