I have created a "Mock" HtmlHelper to hold my model in the ViewDataDictionary. When my test executes the HtmlHelper.TestBoxFor() throws a null reference exception. What am I missing here? ... I thought I had everything mocked up properly.
HtmlHelper Extension
public static MvcHtmlString TextBoxForNonZeroUInt<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
var value = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
if (expression.Body.Type == typeof(uint) && (uint)value == 0)
{
return helper.TextBoxFor(expression, new { Value = "" });
}
return helper.TextBoxFor(expression);
}
Test
[TestClass]
public class TextBoxForNonZeroUIntTests
{
private HtmlHelper<T> CreateHtmlHelper<T>(ViewDataDictionary viewData)
{
var cc = new Mock<ControllerContext>(
new Mock<HttpContextBase>().Object,
new RouteData(),
new Mock<ControllerBase>().Object);
var mockViewContext = new Mock<ViewContext>(
cc.Object,
new Mock<IView>().Object,
viewData,
new TempDataDictionary(),
new Mock<StringWriter>().Object);
var mockViewDataContainer = new Mock<IViewDataContainer>();
mockViewDataContainer.Setup(view => view.ViewData).Returns(viewData);
return new HtmlHelper<T>(mockViewContext.Object, mockViewDataContainer.Object);
}
private class TestSiteDisplayModel
{
public uint SiteId { get; set; }
public string Name { get; set; }
}
[TestMethod]
public void NonUIntWithoutValue_ShouldReturnDefaultTextBoxFor()
{
var viewData = new ViewDataDictionary<TestSiteDisplayModel>
{
Model = new TestSiteDisplayModel {SiteId = 0, Name = "POS BETTER WORK"}
};
var htmlHelper = CreateHtmlHelper<TestSiteDisplayModel>(viewData);
var result = htmlHelper.TextBoxForNonZeroUInt(model => model.SiteId);
}
}
}
Aucun commentaire:
Enregistrer un commentaire