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.
- public static HtmlHelper CreateHtmlHelperOriginal(ViewDataDictionary vd)
- {
- var mockViewContext = new Mock<ViewContext>(
- new ControllerContext(
- new Mock<HttpContextBase>().Object,
- new RouteData(),
- new Mock<ControllerBase>().Object),
- new Mock<IView>().Object,
- vd,
- new TempDataDictionary());
- var mockViewDataContainer = new Mock<IViewDataContainer>();
- mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);
- return new HtmlHelper(mockViewContext.Object,
- mockViewDataContainer.Object);
- }
Here is the modification I needed to make to have my tests run again:
- public static HtmlHelper CreateMockHelper(ViewDataDictionary vd)
- {
- var mockViewContext = new Mock<ViewContext>(
- new ControllerContext(
- new Mock<HttpContextBase>().Object,
- new RouteData(),
- new Mock<ControllerBase>().Object),
- new Mock<IView>().Object,
- vd,
- new TempDataDictionary(),
- new StringWriter());
- var mockViewDataContainer = new Mock<IViewDataContainer>();
- mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);
- return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);
- }
Note the change in line 10 and the addition of line 11:
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.