asp.net-mvc – ASP.net MVC – FluentValidation单元测试
发布时间:2020-12-16 07:27:50 所属栏目:asp.Net 来源:网络整理
导读:我在我的MVC项目中使用FluentValidation并具有以下模型和验证器: [Validator(typeof(CreateNoteModelValidator))]public class CreateNoteModel { public string NoteText { get; set; }}public class CreateNoteModelValidator : AbstractValidatorCreateN
我在我的MVC项目中使用FluentValidation并具有以下模型和验证器:
[Validator(typeof(CreateNoteModelValidator))] public class CreateNoteModel { public string NoteText { get; set; } } public class CreateNoteModelValidator : AbstractValidator<CreateNoteModel> { public CreateNoteModelValidator() { RuleFor(m => m.NoteText).NotEmpty(); } } 我有一个控制器动作来创建注释: public ActionResult Create(CreateNoteModel model) { if( !ModelState.IsValid ) { return PartialView("Test",model); // save note here return Json(new { success = true })); } 我写了一个单元测试来验证行为: [Test] public void Test_Create_With_Validation_Error() { // Arrange NotesController controller = new NotesController(); CreateNoteModel model = new CreateNoteModel(); // Act ActionResult result = controller.Create(model); // Assert Assert.IsInstanceOfType(result,typeof(PartialViewResult)); } 我的单元测试失败,因为它没有任何验证错误.这应该成功,因为model.NoteText为null并且有一个验证规则. 我运行控制器测试时似乎没有运行FluentValidation. 我尝试在测试中添加以下内容: [TestInitialize] public void TestInitialize() { FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(); } 我在Global.asax中使用了相同的行来自动将验证器绑定到控制器……但它似乎不适用于我的单元测试. 我该如何正常工作? 解决方法
这很正常.验证应与控制器操作分开测试,like this.
要测试控制器操作,只需模拟模型状态错误: [Test] public void Test_Create_With_Validation_Error() { // Arrange NotesController controller = new NotesController(); controller.ModelState.AddModelError("NoteText","NoteText cannot be null"); CreateNoteModel model = new CreateNoteModel(); // Act ActionResult result = controller.Create(model); // Assert Assert.IsInstanceOfType(result,typeof(PartialViewResult)); } 控制器不应该对流畅的验证有任何了解.您需要在此测试的是,如果模型状态中存在验证错误,则控制器操作的行为正确.如何将此错误添加到模型状态是另一个需要单独测试的问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – Global.asax.cs事件在网站发布后未触发
- asp.net – Context中不存在DeleteObject
- asp.net – 我们可以在视图状态中放置哪些类型的对象?
- asp.net-web-api – 如何记录webapi中控制器中执行的操作方
- 您是否可以覆盖Date.Now或Date.Today以在ASP.NET Web应用程
- asp.net – 为什么在IIS已经处理请求并发时使用异步控制器?
- asp.net-mvc – 为什么我的MVC应用程序中有两个web.config文
- asp.net-mvc – ASP.NET MVC – 模型可以有业务逻辑吗?
- asp-classic – 你用什么来编辑和开发经典ASP
- ASP.NET MembershipProvider加密/解密