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.

  1.  
  2. public static HtmlHelper CreateHtmlHelper(ViewDataDictionary vd)
  3. {
  4.   var mockViewContext = new Mock<ViewContext>(
  5.     new ControllerContext(
  6.       new Mock<HttpContextBase>().Object,
  7.       new RouteData(),
  8.       new Mock<ControllerBase>().Object),
  9.     new Mock<IView>().Object,
  10.     vd,
  11.     new TempDataDictionary());
  12.  
  13.   var mockViewDataContainer = new Mock<IViewDataContainer>();
  14.   mockViewDataContainer.Setup(v => v.ViewData)
  15.     .Returns(vd);
  16.  
  17.   return new HtmlHelper(mockViewContext.Object,
  18.     mockViewDataContainer.Object);
  19. }
  20.  

3 Comments so far »

  1. Steve said

    on August 5 2009 at 19:05

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

  2. Steve said

    on August 5 2009 at 19:10

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

  3. Håvard said

    on August 9 2009 at 01:04

    Thanks for spotting, updated now.

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment:

Get Adobe Flash playerPlugin by wpburn.com wordpress themes