For those of you trying to mock HtmlHelper, but finding it difficult, here’s a mock that works in ASP.NET MVC RC1.
The ViewDataDictionary that is passed to the HtmlHelper can be empty, or made to contain the data you want for your test.
public static HtmlHelper CreateHtmlHelper(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());</p>
<p>var mockViewDataContainer = new Mock<IViewDataContainer>();
mockViewDataContainer.Setup(v => v.ViewData)
.Returns(vd);</p>
<p>return new HtmlHelper(mockViewContext.Object,
mockViewDataContainer.Object);
}
This code does not compile because the viewData variable on line 15 does not exist.
But I’m presuming the “viewData” variable on line 15 was intended to be “vd”.
Thanks for spotting, updated now.