• Post Calendar

    February 2010
    S M T W T F S
    « Jan   Mar »
     123456
    78910111213
    14151617181920
    21222324252627
    28  

Testing HtmlHelper in MVC 2 RC 2

Technorati Tags: ,,,

I strive to use TDD (Test Driven Development) so not having unit tests drives me crazy. I was so pleased to run across this post http://ox.no/posts/mocking-htmlhelper-in-aspnet-mvc-rc1-using-moq making it easy for me to unit test the Html Helper.

But then I downloaded the MVC 2 RC 2 and all my unit tests for HtmlHelper broke! It was late at night and I was getting errors that made it sound like there was an issue with a method I could not override. After looking more closely it looks like a TextWrite parameter was added to the constructor of the HtmlHelper.

  1. public static HtmlHelper CreateHtmlHelperOriginal(ViewDataDictionary vd)
  2. {
  3.     var mockViewContext = new Mock<ViewContext>(
  4.       new ControllerContext(
  5.             new Mock<HttpContextBase>().Object,
  6.             new RouteData(),
  7.             new Mock<ControllerBase>().Object),
  8.         new Mock<IView>().Object,
  9.         vd,
  10.         new TempDataDictionary());
  11.  
  12.     var mockViewDataContainer = new Mock<IViewDataContainer>();
  13.     mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);
  14.  
  15.     return new HtmlHelper(mockViewContext.Object,
  16.       mockViewDataContainer.Object);
  17. }

Here is the modification I needed to make to have my tests run again:

  1. public static HtmlHelper CreateMockHelper(ViewDataDictionary vd)
  2. {
  3.     var mockViewContext = new Mock<ViewContext>(
  4.         new ControllerContext(
  5.             new Mock<HttpContextBase>().Object,
  6.             new RouteData(),
  7.             new Mock<ControllerBase>().Object),
  8.         new Mock<IView>().Object,
  9.         vd,
  10.         new TempDataDictionary(),
  11.         new StringWriter());
  12.  
  13.     var mockViewDataContainer = new Mock<IViewDataContainer>();
  14.     mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);
  15.  
  16.     return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);
  17. }

Note the change in line 10 and the addition of line 11:

image

I thank Håvard Stranden for their original post and hope this one might help others that prefer well tested code that are using MVC 2 RC 2.

Leave a Comment