0

We use FluentValidation for input validation in our ASP.NET Core MVC controllers. Since the validators are a critical part of the system from a security point of view, we'd like to create unit tests that ensure that validation in actually active, and that the right validator is used for each controller.

We enable FluentValidation as usual in Startup.cs:

services.AddMvc(...).AddFluentValidation(...);

I haven't been able to find anything about this, only about unit testing the validators directly, which is a different case.

How do we unit-test the validation chain?

0

1 Answer 1

0

Its expected behavior, validations are supposed to be tested separately from controller actions and to test your controller action simply you can simulate a model state error.

[Test]
public void Test_Validation_Error()
{

    //Arrange
    Controller controllerInstance = new Controller(); //Or use dependency injection in test project and use the instance thereafter.
    controllerInstance.ModelState.AddModelError("Model_Property_Name","Expected_Error_Message");
    CreatedModel model = new CreatedModel(); // Whose property we are validating.

    //Act
    ActionResult result = controllerInstance.Create(model);

    //Assert
    Assert.IsInstanceOfType(result,typeof(PartialViewResult));
}

A controller doesn't know about fluent validation, the testing here should separately be here if validation error in model state of your controller action behaves correctly. For a chain of validation the different model properties on which the validations are supposed to be fired should be added in the "AddModelError" section.

Hope this helps !! Happy coding :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.