调用 HtmlHelper 的单元测试中的 NullReferenceException
我编写了一个 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/
I wrote an HtmlHelper which in-turn calls Html.TextBoxFor(). However, when I execute the test I'm getting a null ref exception. I'm assuming that I'm creating the HtmlHelper incorrectly but I can't figure out what is wrong.
I have simplified the code as much as possible:
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" });
}
The exception is being called at helper.TextBoxFor(). Anyone see anything that looks to be wrong?
I grabbed the CreateHtmlHelper method from http://joyofexcellence.com/blog/index.php/2010/02/27/testing-htmlhelper-in-mvc-2-rc-2/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论