8 Mar, 2009
C#, Code, Technical
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 Mock<HttpContextBase>
().
Object,
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);
}
Steve said
on August 5 2009 at 19:05
This code does not compile because the viewData variable on line 15 does not exist.
Steve said
on August 5 2009 at 19:10
But I’m presuming the “viewData” variable on line 15 was intended to be “vd”.
Håvard said
on August 9 2009 at 01:04
Thanks for spotting, updated now.