I use FluentValidation in my MVC project and have the following model and validator:
[Validator(typeof(CreateNoteModelValidator))] public class CreateNoteModel { public string NoteText { get; set; } } public class CreateNoteModelValidator : AbstractValidator<CreateNoteModel> { public CreateNoteModelValidator() { RuleFor(m => m.NoteText).NotEmpty(); } }
I have a controller action to create a note:
public ActionResult Create(CreateNoteModel model) { if( !ModelState.IsValid ) { return PartialView("Test", model); // save note here return Json(new { success = true })); }
I wrote unit test to test the behavior:
[Test] public void Test_Create_With_Validation_Error() {
My unit test does not work as it does not have validation errors. This should be successful because model.NoteText is null and there is a validation rule for this.
It seems that FluentValidation does not work when I run my control test.
I tried to add the following to my test:
[TestInitialize] public void TestInitialize() { FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(); }
I have the same line in my Global.asax to automatically bind validators to controllers ... but it does not work in my unit test.
How can I make this work correctly?
source share