我正在尝试测试我编写的一些HtmlHelper
扩展方法。我的第一个问题是如何创建一个HtmlHelper
实例,但我使用了以下代码解决了这个问题:
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);
}
我的几个测试现在都很好,但有一个测试会抛出异常。该测试定义如下:
// Arrange
var inputDictionary = CreateDictionary();
var htmlHelper = CreateHtmlHelper(inputDictionary);
// Act
var actualHtmlString = htmlHelper.EditorFor(m => m.Dict, model).ToHtmlString();
...
< p > EditorFor
方法是我的扩展方法。在该方法的某处,调用了以下内容:
tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(expression, metadata));
当我从我的单元测试中执行这段代码时,会抛出以下异常:
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
因此,代码在ScopeCache.Get
中失败了,但是为什么?有人有解决方法吗?