【发布时间】:2014-08-08 15:03:50
【问题描述】:
我正在尝试测试我编写的一些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();
...
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 中失败了,但为什么呢?有谁知道如何解决这个问题?
【问题讨论】:
标签: c# asp.net-mvc unit-testing html-helper