这是故事。为了能够将格式良好的 Bootstrap 控件放入我的 MVC 表单中,我正在构建一个HtmlHelper
扩展方法,该方法使用单个命令生成以下结构:
<div class="control-group">
@Html.LabelFor(m => m.UserName, new { @class = "control-label" })
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
@Html.TextBoxFor(m => m.UserName, new { @class = "input-xlarge" })
</div>
@Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
方法本身并不难写。更困难的是单元测试。为了使我的扩展方法可测试,我需要创建一个HtmlHelper<T>
使用适当模拟的实例。为此,我调整了一个旧 StackOverflow 问题的答案并提出了这个:
public static HtmlHelper<TModel> CreateHtmlHelper<TModel>(bool clientValidationEnabled, bool unobtrusiveJavascriptEnabled, ViewDataDictionary dictionary = null)
{
if (dictionary == null)
dictionary = new ViewDataDictionary { TemplateInfo = new TemplateInfo() };
var mockViewContext = new Mock<ViewContext>(
new ControllerContext(
new Mock<HttpContextBase>().Object,
new RouteData(),
new Mock<ControllerBase>().Object),
new Mock<IView>().Object,
dictionary,
new TempDataDictionary(),
new Mock<TextWriter>().Object);
mockViewContext.SetupGet(c => c.UnobtrusiveJavaScriptEnabled).Returns(unobtrusiveJavascriptEnabled);
mockViewContext.SetupGet(c => c.FormContext).Returns(new FormContext { FormId = "myForm" });
mockViewContext.SetupGet(c => c.ClientValidationEnabled).Returns(clientValidationEnabled);
mockViewContext.SetupGet(c => c.ViewData).Returns(dictionary);
var mockViewDataContainer = new Mock<IViewDataContainer>();
mockViewDataContainer.Setup(v => v.ViewData).Returns(dictionary);
return new HtmlHelper<TModel>(mockViewContext.Object, mockViewDataContainer.Object);
}
到目前为止,一切都很好。现在我可以创建一个HtmlHelper
对象,我可以按如下方式执行我的测试:
// ARRANGE
ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
var helper = MvcMocks.CreateHtmlHelper<TestModel>(true, true);
helper.ViewData.Model = new TestModel { Field = null };
helper.ViewData.ModelState.AddModelError("Field", "The field must be assigned.");
// ACT
var controlGroup = helper.ControlGroupFor(m => m.Field, CssClasses.IconUser).ToHtmlString();
这是问题所在。内ControlGroupFor
,其签名为
public static HtmlString ControlGroupFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string iconClass)
并且我还没有完成(作为一个优秀的小型 TDD 开发人员),我正在调用var validationMessage = html.ValidationMessageFor(expression)
. 尽管我使用了AddModelError
,但该ValidationMessageFor
方法似乎认为它html.ViewData.ModelState["Field"]
要么为空,要么它的ModelErrors
集合为空。我推断这是validationMessage
因为
<span class="field-validation-valid" data-valmsg-for="Field" data-valmsg-replace="true"></span>
根据 Resharper 的说法,该ValidationMessageFor
方法调用此方法:
private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary<string, object> htmlAttributes)
{
string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();
if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)
{
return null;
}
ModelState modelState = htmlHelper.ViewData.ModelState[modelName];
ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;
ModelError modelError = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);
if (modelError == null && formContext == null)
{
return null;
}
TagBuilder builder = new TagBuilder("span");
builder.MergeAttributes(htmlAttributes);
builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);
if (!String.IsNullOrEmpty(validationMessage))
{
builder.SetInnerText(validationMessage);
}
else if (modelError != null)
{
builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState));
}
if (formContext != null)
{
bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);
if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
{
builder.MergeAttribute("data-valmsg-for", modelName);
builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
}
else
{
FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);
// rules will already have been written to the metadata object
fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified
// client validation always requires an ID
builder.GenerateId(modelName + "_validationMessage");
fieldMetadata.ValidationMessageId = builder.Attributes["id"];
}
}
return builder.ToMvcHtmlString(TagRenderMode.Normal);
}
现在,根据我所做的一切,validationMessage
应该给我一个span
带有类field-validation-error
的错误消息,上面写着“必须分配该字段”。在我的监视窗口中,html.ViewData.ModelState["Field"].Errors
计数为 1。我一定错过了一些东西。谁能看到它是什么?