我写了一个HtmlHelper,它反过来调用Html.TextBoxFor()。但是,当我执行测试时,我得到一个空引用异常。我假设我正在错误地创建HtmlHelper但我无法弄清楚出了什么问题。
我尽可能地简化了代码:
public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData = null, TModel model = null) where TModel : class, new()
{
if (viewData == null)
viewData = new ViewDataDictionary(model ?? new TModel());
Mock mockViewContext = new Mock(
new ControllerContext(
new Mock().Object,
new RouteData(),
new Mock().Object),
new Mock().Object,
viewData,
new TempDataDictionary(),
new StringWriter());
var mockViewDataContainer = new Mock();
mockViewDataContainer
.Setup(v => v.ViewData)
.Returns(viewData);
return new HtmlHelper(mockViewContext.Object, mockViewDataContainer.Object);
}
[TestMethod]
public void ReadOnlyTextBox_Returns_ReadOnly_Textbox()
{
var cl = new Class1();
var helper = CreateHtmlHelper(model: cl);
MvcHtmlString result = helper.ReadOnlyTextBox(m => m.First);
Assert.IsNotNull(result);
}
public static MvcHtmlString ReadOnlyTextBox(this HtmlHelper helper, Expression> expr)
{
// Do some stuff
return helper.TextBoxFor(expr, new { @readonly = "readonly", @disabled = "disabled" });
}
在helper.TextBoxFor()中调用异常。有人看到任何看起来错了吗? 我从http://joyofexcellence.com/blog/index.php/2010/02/27/testing-htmlhelper-in-mvc-2-rc-2/
抓取了CreateHtmlHelper方法