Asp.net mvc ASP.net MVC-FluentValidation单元测试
我在MVC项目中使用FluentValidation,并拥有以下模型和验证器:Asp.net mvc ASP.net MVC-FluentValidation单元测试,asp.net-mvc,asp.net-mvc-3,unit-testing,fluentvalidation,Asp.net Mvc,Asp.net Mvc 3,Unit Testing,Fluentvalidation,我在MVC项目中使用FluentValidation,并拥有以下模型和验证器: [Validator(typeof(CreateNoteModelValidator))] public class CreateNoteModel { public string NoteText { get; set; } } public class CreateNoteModelValidator : AbstractValidator<CreateNoteModel> { pu
[Validator(typeof(CreateNoteModelValidator))]
public class CreateNoteModel {
public string NoteText { get; set; }
}
public class CreateNoteModelValidator : AbstractValidator<CreateNoteModel> {
public CreateNoteModelValidator() {
RuleFor(m => m.NoteText).NotEmpty();
}
}
我编写了一个单元测试来验证行为:
[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中也有同样的代码,可以自动将验证器绑定到控制器上……但在我的单元测试中它似乎不起作用
如何使其正常工作?这很正常。验证应与控制器操作分开进行测试 要测试控制器操作,只需模拟modelstate错误:
[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));
}
控制器不应该真正了解任何有关fluent验证的信息。这里需要测试的是,如果modelstate中存在验证错误,那么控制器操作将正常运行。如何将此错误添加到modelstate是另一个需要单独测试的问题。Ahh谢谢。我没有想到像这样在测试中添加模型错误。谢谢你,达林。
[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));
}