11 August, 2010

Mocking HtmlHelper in ASP.NET MVC 2 and 3 using Moq

Still having trouble mocking HtmlHelper? This is an update to my previous post on mocking HtmlHelper way back when ASP.NET MVC RC1 was released. Eric notified me through a comment on the post and a question on StackOverflow that the code for ASP.NET MVC RC1 did not work with ASP.NET MVC 2. The code in this post should work with ASP.NET MVC 2 and ASP.NET MVC 3 Preview 1.

public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd)
{
Mock mockViewContext = new Mock(
new ControllerContext(
new Mock().Object,
new RouteData(),
new Mock().Object),
new Mock().Object,
vd,
new TempDataDictionary(),
new Mock().Object);
var mockViewDataContainer = new Mock();
mockViewDataContainer.Setup(v => v.ViewData)
.Returns(vd);
return new HtmlHelper(mockViewContext.Object,
mockViewDataContainer.Object);
}

2 comments: