我在我的 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 中有同样的行,可以自动将验证器绑定到控制器......但它似乎在我的单元测试中不起作用。
我怎样才能让它正常工作?