Mocking HtmlHelper in ASP.NET MVC RC1 using Moq

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 entry was posted in C#, Code, Technical and tagged , , , , , , , . Bookmark the permalink.

5 Responses to Mocking HtmlHelper in ASP.NET MVC RC1 using Moq

  1. Steve says:

    This code does not compile because the viewData variable on line 15 does not exist.

  2. Steve says:

    But I’m presuming the “viewData” variable on line 15 was intended to be “vd”.

  3. Håvard says:

    Thanks for spotting, updated now.

  4. Eric says:

    Hi, I’ve been trying to use your code, but I am having some problems when HtmlHelper is instanciated.

    I’ve detailed the problem here: http://stackoverflow.com/questions/3445770/missingmethodexception-thrown-when-trying-to-mock-htmlhelper-with-moq

    apparently the ViewContext constructor’s signature has changed, but even when supplying an updated Mock, I’m seeing a MissingMethodException being thrown.

  5. Pingback: Mocking HtmlHelper in ASP.NET MVC 2 and 3 using Moq | Circles and Crosses

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>