In the previous posts, we’ve learned how to create validators. Set the required rules and build custom validators. To finish learning using the fluent validation library, we’ll write some tests to be sure that we defined rules properly.
Unit test extensions
The validation library consists of two extension methods for validators which allow checking if a validator has or not any error for the chosen property.
There are a few methods to use:
ShouldHaveValidationErrorForShouldNotHaveValidationErrorForShouldHaveChildValidator
Basic usage
In the following lines, I’ll show some examples of how they can be used. At the start we need model:
class TestModel {
public string Text { get; set; }
public int[] Numbers { get; set; }
}
Let’s start with rule for Text property:
RuleFor(x => x.Text)
.NotEmpty()
.WithErrorCode("NotEmptyErrorCode")
.WithMessage("Text cannot be empty");
Then in a unit test, we create a validator and call methods on it, for example:
validator = new TestValidator();
// checks value
validator.ShouldHaveValidationErrorFor(x => x.Text, "");
// checks property in TestModel object
validator.ShouldHaveValidationErrorFor(x => x.Text, new TestModel());
// no error for correct value
validator.ShouldNotHaveValidationErrorFor(x => x.Text, "text");
Error result value check
Furthermore, there is a possibility to add additional checks for validation results. It is done by exceeding the previous example.
validator.ShouldHaveValidationErrorFor(x => x.Text, "")
.WithErrorCode("NotEmptyErrorCode")
.WithErrorMessage("Text cannot be empty");
Child validator
In addition, the last unit test presented in this post shows how to assure there is proper child validator assign.
// rule
RuleFor(x => x.Numbers)
.SetValidator(new ChildTestValidator());
// assertion
validator.ShouldHaveChildValidator(
x => x.Numbers, typeof(ChildTestValidator));
I think that after this post I’ve summarized most of the things that can be done using the FluentValidation library. For more information, you can use official documentation. All codes used for fluent validation posts can be found here.