Mocking HtmlHelper throws NullReferenceException

Posted by Matt Austin on Stack Overflow See other posts from Stack Overflow or by Matt Austin
Published on 2013-06-25T18:30:57Z Indexed on 2013/06/25 22:21 UTC
Read the original article Hit count: 283

I know that there are a few questions on StackOverflow on this topic but I haven't been able to get any of the suggestions to work for me. I've been banging my head against this for two days now so its time to ask for help...

The following code snippit is a simplified unit test to demonstrate what I'm trying to do, which is basically call RadioButtonFor in the Microsoft.Web.Mvc assembly in a unit test.

var model = new SendMessageModel
                  {
                       SendMessageType = SendMessageType.Member
                  };

var vd = new ViewDataDictionary(model);
vd.TemplateInfo = new TemplateInfo { HtmlFieldPrefix = string.Empty };

var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object,
                                              new RouteData(),
                                              new Mock<ControllerBase>().Object);

var viewContext = new Mock<ViewContext>(new object[] { controllerContext, new Mock<IView>().Object, vd, new TempDataDictionary(), new Mock<TextWriter>().Object });
viewContext.Setup(v => v.View).Returns(new Mock<IView>().Object);
viewContext.Setup(v => v.ViewData).Returns(vd).Callback(() => {throw new Exception("ViewData extracted");});
viewContext.Setup(v => v.TempData).Returns(new TempDataDictionary());
viewContext.Setup(v => v.Writer).Returns(new Mock<TextWriter>().Object);
viewContext.Setup(v => v.RouteData).Returns(new RouteData());
viewContext.Setup(v => v.HttpContext).Returns(new Mock<HttpContextBase>().Object);
viewContext.Setup(v => v.Controller).Returns(new Mock<ControllerBase>().Object);
viewContext.Setup(v => v.FormContext).Returns(new FormContext());

var mockContainer = new Mock<IViewDataContainer>();
mockContainer.Setup(x => x.ViewData).Returns(vd);

var helper = new HtmlHelper<ISendMessageModel>(viewContext.Object, mockContainer.Object, new RouteCollection());
helper.RadioButtonFor(m => m.SendMessageType, "Member", cssClass: "selector"); 

If I remove the cssClass parameter then the code works ok but fails consistently when adding additional parameters.

I've tried every combination of mocking, instantiating concrete types and using fakes that I can think off but I always get a NullReferenceException when I call RadioButtonFor. Any help hugely appreciated!!

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc