08 March, 2009

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.

5 comments:

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

    ReplyDelete
  2. But I'm presuming the "viewData" variable on line 15 was intended to be "vd".

    ReplyDelete
  3. Thanks for spotting, updated now.

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Eric,

    check out a version for MVC 2 and 3 in this new post.

    ReplyDelete