gpt4 book ai didi

asp.net-mvc-3 - 单元测试 HtmlHelper 自定义 TextBoxFor

转载 作者:行者123 更新时间:2023-12-04 09:24:28 24 4
gpt4 key购买 nike

我创建了一个扩展方法,它将返回 html 助手 TextBoxFor。现在我想对其进行单元测试,但它抛出“对象引用未设置为对象的实例”。

扩展方法

public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper htmlHelper,     .......)
{

/* some logic here */
===> (Null Exception)
return htmlHelper.TextBoxFor(......);
}

HtmlHelper 模拟是正确的,因为我在几个地方使用过它。

最佳答案

无需模拟 HtmlHelper。您可以只创建一个假的 View 模型类,例如 TestViewModel 并在您的单元测试中执行如下操作:

//-- Arrange
TestViewModel testViewModel = new TestViewModel()
{
Name = "sdfsd"
};

IViewDataContainer dataContainerMock = MockRepository.GenerateStub<IViewDataContainer>();

dataContainerMock.ViewData = new ViewDataDictionary<TestViewModel>(testViewModel);

HtmlHelper<TestViewModel> myHelper = new HtmlHelper<TestViewModel>(new ViewContext()
{
ViewData = new ViewDataDictionary<TestViewModel>(this._testViewModelWithoutMaxLength)
}, this._dataContainerMock);

//-- Act
MvcHtmlString result = //call your extension

//-- Assert
//add asserts here

有点晚了,但希望对某人来说还可以

关于asp.net-mvc-3 - 单元测试 HtmlHelper 自定义 TextBoxFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5594171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com