ASP.net MVC - FluentValidation Unit Test Tests

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() { // Arrange NotesController controller = new NotesController(); CreateNoteModel model = new CreateNoteModel(); // Act ActionResult result = controller.Create(model); // Assert Assert.IsInstanceOfType(result, typeof(PartialViewResult)); } 

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?

+4
source share
1 answer

This is normal. Validation must be validated separately from controller actions like this .

And to check the action of your controller, just simulate a modelstate error:

 [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)); } 

The controller should not know anything about free checking. The ones you need to check here is that if there is a validation error in the model file, the behavior of your controller behaves correctly. As this error was added to the model state, another problem is that shoulod is tested separately.

+10
source

All Articles