How to Unit Test HtmlHelper with Moq?

DaveDev picture DaveDev · Mar 22, 2010 · Viewed 7.9k times · Source

Could somebody show me how you would go about creating a mock HTML Helper with Moq?

This article has a link to an article claiming to describe this, but following the link only returns an ASP.NET Runtime Error

[edit] I asked a more specific question related to the same subject here, but it hasn't gotten any responses. I figured it was too specific, so I thought I could get a more general answer to a more general question and modify it to meet my requirements.

Thanks

Answer

Thomas picture Thomas · Mar 23, 2010

Here's another article that shows you how to achieve the same thing:

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());

  var mockViewDataContainer = new Mock<IViewDataContainer>();
  mockViewDataContainer.Setup(v => v.ViewData).Returns(vd);

  return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);
}