Asp.net mvc 3 单元测试HtmlHelper自定义文本框
我创建了一个扩展方法,它将返回html helper TextBoxFor。现在我想对其进行单元测试,但它抛出“对象引用未设置为对象的实例” 扩展方法Asp.net mvc 3 单元测试HtmlHelper自定义文本框,asp.net-mvc-3,unit-testing,html-helper,Asp.net Mvc 3,Unit Testing,Html Helper,我创建了一个扩展方法,它将返回html helper TextBoxFor。现在我想对其进行单元测试,但它抛出“对象引用未设置为对象的实例” 扩展方法 public static MvcHtmlString TextBoxFor(此HtmlHelper HtmlHelper,…) { /*这里有些逻辑*/ =>(空异常) 返回(……)的htmlHelper.textbox; } HtmlHelper模拟是正确的,因为我在几个地方使用过它。无需模拟HtmlHelper。您可以只创建一个假视图模型
public static MvcHtmlString TextBoxFor(此HtmlHelper HtmlHelper,…)
{
/*这里有些逻辑*/
=>(空异常)
返回(……)的htmlHelper.textbox;
}
HtmlHelper模拟是正确的,因为我在几个地方使用过它。无需模拟HtmlHelper。您可以只创建一个假视图模型类,例如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
/--Arrange
TestViewModel TestViewModel=新的TestViewModel()
{
Name=“sdfsd”
};
IViewDataContainer dataContainerMock=MockRepository.GenerateSub();
dataContainerMock.ViewData=新的ViewDataDictionary(testViewModel);
HtmlHelper myHelper=新的HtmlHelper(新的ViewContext()
{
ViewData=new ViewDataDictionary(此.\u TestViewModelWithout MaxLength)
},这个。_dataContainerMock);
//--表演
MvcHtmlString result=//调用您的扩展名
//--断言
//在此处添加资产
有点晚了,但希望对某人来说还是可以的请你再添加一些代码。为扩展方法添加更多代码。查看单元测试会有帮助,因为你的问题可能是你没有实例化
HtmlHelper
properlyPerfect,有同样的问题,这是我需要的,非常感谢。MockRepository来自哪里?在哪里可以找到测试项目?
//-- 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