Lesson 59 of 93 · 6 min read · Updated
Unit Testing FluentValidation Validators Directly with TestValidate
On this page
Validation rules are logic, and logic deserves its own tests. If you only test them through a controller, every rule needs a mock repository, a controller instance and an ActionResult assertion. This lesson tests a FluentValidation validator directly with the built-in TestValidate helpers, so each rule gets a short, fast test that names the property it is about.
Technical Requirements
- .NET 11 SDK
- FluentValidation 12.2.0 (Apache-2.0; the test helpers ship in the same package, in the
FluentValidation.TestHelpernamespace) - xUnit 2.9.3
No mocking library is needed. The validator has no dependencies, so the test creates it with new.
The Validator Under Test
The validator describes what a valid CreateProductRequest looks like. It covers the name, the price, the stock and an optional e-mail address.
M07.WebApp/Validation/CreateProductRequestValidator.cs
The messages are in Turkish. In English they read: "Product name is required", "must be at least 3 characters", "at most 100 characters", "Price must be positive", "Price cannot be above 1000000", "Stock cannot be negative" and "Enter a valid e-mail address". The upper price limit comes from PricingRules.MaxPrice, so the validator and the business rule share one constant instead of two copies of the same number.
The application registers the validator in dependency injection:
M07.WebApp/Program.cs
The tests do not use that registration. They create the validator directly.
Start from a Valid Request
Each test changes exactly one property of a request that is otherwise valid. A small factory method gives every test the same valid starting point.
M07.WebApp.Tests/ValidatorTests.cs
Why start from a valid object? If the base request were already invalid, a failing result would hold several errors, and it would be hard to tell which change caused which. The first test, Validate_WithValidRequest_HasNoErrors, guards that base. If someone adds a rule that the sample request breaks, this test fails first and tells you to update ValidRequest().
xUnit creates a new instance of the test class for every test, so the _validator field is never shared between tests. The validator has no state, but the habit keeps tests isolated.
Testing Each Rule and Its Boundary
TestValidate runs the validator and returns a TestValidationResult<T>. ShouldHaveValidationErrorFor(x => x.Name) fails unless there is an error for that exact property. That is more precise than checking IsValid == false, which would pass for an error on any property.
M07.WebApp.Tests/ValidatorTests.cs
The name tests cover both sides of the boundary. Two characters fail; three characters pass. A test for only one side would let an off-by-one mistake through: MinimumLength(4) would still fail for "ab".
The price test chains .WithErrorMessage(...) to check the message as well. Use this when the message text is part of what the user sees and you want to protect it. For rules where only the property matters, leave it out so that a wording change does not break the test.
Conditional Rules Need Two Tests
The e-mail rule has a When condition. A conditional rule has two behaviours, so it needs two tests: one where the condition is true and the rule fires, and one where the condition is false and the rule is skipped.
M07.WebApp.Tests/ValidatorTests.cs
The value gecersiz-eposta means "invalid-email". A common mistake is to test only the invalid e-mail. If someone later removes the When clause, users who leave the optional field empty would be blocked, and only the second test would catch it.
Async Validation Works the Same Way
If a validator has asynchronous rules, such as MustAsync, you must call it through TestValidateAsync. The assertions are the same.
M07.WebApp.Tests/ValidatorTests.cs
These tests stay separate from the controller tests. Validation rules live here; the controller's "what do I do when the model is invalid" flow lives in the controller tests. When a rule changes, only this file changes.
Summary
- Test FluentValidation validators directly with
TestValidateandTestValidateAsync; no controller and no mocks are needed. - Start each test from a valid request and change one property, so each failure has one cause.
- Use
ShouldHaveValidationErrorForandShouldNotHaveValidationErrorForto check the exact property, andWithErrorMessagewhen the text matters. - Test both sides of every boundary, such as two and three characters for a minimum length of three.
- A conditional
Whenrule needs one test where it fires and one where it is skipped.