I am trying to check out some of the HtmlHelper extension methods that I wrote. My first problem was how to create an instance of HtmlHelper , but I decided that using this code:
private static HtmlHelper<T> CreateHtmlHelper<T>(T model) { var viewDataDictionary = new ViewDataDictionary(model); var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object, new RouteData(), new Mock<ControllerBase>().Object); var viewContext = new ViewContext(controllerContext, new Mock<IView>().Object, viewDataDictionary, new TempDataDictionary(), new Mock<TextWriter>().Object); var mockViewDataContainer = new Mock<IViewDataContainer>(); mockViewDataContainer.Setup(v => v.ViewData).Returns(viewDataDictionary); return new HtmlHelper<T>(viewContext, mockViewDataContainer.Object); }
Several of my tests now work fine, but there is one test that throws an exception. The test is defined as follows:
The EditorFor method is my extension method. Somewhere in this method, the following call is made:
tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(expression, metadata));
This is that when this code is executed from my unit test, the following exception is thrown:
System.NullReferenceExceptionObject reference not set to an instance of an object. at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext) at System.Web.Mvc.ViewContext.get_UnobtrusiveJavaScriptEnabled() at System.Web.Mvc.HtmlHelper.GetUnobtrusiveValidationAttributes(String name, ModelMetadata metadata) at AspNetMvcDictionarySerialization.HtmlHelperExtensions.InputTagHelper(HtmlHelper htmlHelper, ModelMetadata metadata, InputType inputType, String expression, IDictionary`2 htmlAttributes, String fullName, Int32 index, String fieldType, String val) in HtmlHelperExtensions.cs: line 154
Thus, the code does not work in ScopeCache.Get , but why? Does anyone know how to solve this?
c # unit-testing asp.net-mvc html-helper
Erik Schierboom Aug 08 '14 at 15:03 2014-08-08 15:03
source share