【发布时间】:2014-03-21 14:41:12
【问题描述】:
我已经为 ASP.NET MVC Web 应用程序编写了我的第一个单元测试。一切正常,它为我提供了有价值的信息,但我无法测试视图模型中的错误。 ModelState.IsValid 始终为 true,即使某些值未填写(空字符串或 null)。
我已经读过模型验证发生在发布的数据映射到模型时,您需要编写一些代码来自己进行模型验证:
我已经尝试了链接网页中提供的三个示例,但似乎对我不起作用。
一些代码:
我的视图模型
...
[Required(ErrorMessageResourceName = "ErrorFirstName", ErrorMessageResourceType = typeof(Mui))]
[MaxLength(50)]
[Display(Name = "Firstname", ResourceType = typeof(Mui))]
public string FirstName { get; set; }
...
控制器
...
[HttpPost]
public ActionResult Index(POSViewModel model)
{
Contract contract = contractService.GetContract(model.ContractGuid.Value);
if (!contract.IsDirectDebit.ToSafe())
{
ModelState.Remove("BankName");
ModelState.Remove("BankAddress");
ModelState.Remove("BankZip");
ModelState.Remove("BankCity");
ModelState.Remove("AccountNr");
}
if (ModelState.IsValid)
{
...
contractValidationService.Create(contractValidation);
unitOfWork.SaveChanges();
return RedirectToAction("index","thanks");
}
else
{
return Index(model.ContractGuid.ToString());
}
}
我的单元测试
posViewModel.FirstName = null;
posViewModel.LastName = "";
...
var modelBinder = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => posViewModel, posViewModel.GetType()),
ValueProvider = new NameValueCollectionValueProvider(new System.Collections.Specialized.NameValueCollection(), CultureInfo.InvariantCulture)
};
var binder = new DefaultModelBinder().BindModel(new ControllerContext(), modelBinder);
posController.ModelState.Clear();
posController.ModelState.Merge(modelBinder.ModelState);
ActionResult result = posController.Index(posViewModel);
//Assert
mockContractValidationService.Verify(m => m.Create(It.IsAny<ContractValidation>()), Times.Never);
Assert.IsInstanceOfType(result, typeof(ViewResult));
在视图中,我正在使用不显眼的 JavaScript 验证,并且它有效。
【问题讨论】:
-
@JasonEvans 我已经尝试过了,这是 Scott Hanselmann 在 SO 链接上提供的解决方案。
标签: c# asp.net-mvc unit-testing modelstate