Lesson 59 of 93 · 6 min read · Updated

Unit Testing FluentValidation Validators Directly with TestValidate

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

  1. .NET 11 SDK
  2. FluentValidation 12.2.0 (Apache-2.0; the test helpers ship in the same package, in the FluentValidation.TestHelper namespace)
  3. 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

/// <summary>
/// Validation rules should be tested INDEPENDENTLY of the controller flow.
/// That way neither the number of tests nor their run time is loaded onto the controller.
/// </summary>
public sealed class CreateProductRequestValidator : AbstractValidator<CreateProductRequest>
{
public CreateProductRequestValidator()
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Ürün adı zorunludur.")
.MinimumLength(3).WithMessage("Ürün adı en az 3 karakter olmalıdır.")
.MaximumLength(100).WithMessage("Ürün adı en fazla 100 karakter olabilir.");

RuleFor(x => x.Price)
.GreaterThan(0).WithMessage("Fiyat pozitif olmalıdır.")
.LessThanOrEqualTo(PricingRules.MaxPrice)
.WithMessage($"Fiyat {PricingRules.MaxPrice:0} üzerinde olamaz.");

RuleFor(x => x.Stock)
.GreaterThanOrEqualTo(0).WithMessage("Stok negatif olamaz.");

// Conditional rule: the e-mail is validated only IF IT IS FILLED IN.
RuleFor(x => x.NotificationEmail)
.EmailAddress().WithMessage("Geçerli bir e-posta adresi giriniz.")
.When(x => !string.IsNullOrWhiteSpace(x.NotificationEmail));
}
}

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

builder.Services.AddScoped<IValidator<M07.WebApp.Models.CreateProductRequest>, CreateProductRequestValidator>();

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

public class ValidatorTests
{
private readonly CreateProductRequestValidator _validator = new();

private static CreateProductRequest ValidRequest() => new()
{
Name = "Mekanik Klavye",
Price = 750m,
Stock = 10,
};

[Fact]
public void Validate_WithValidRequest_HasNoErrors()
{
var result = _validator.TestValidate(ValidRequest());

result.ShouldNotHaveAnyValidationErrors();
}
}

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

[Theory]
[InlineData("")]
[InlineData("ab")] // minimum 3 characters
public void Validate_WithTooShortName_HasErrorForName(string name)
{
var request = ValidRequest();
request.Name = name;

var result = _validator.TestValidate(request);

result.ShouldHaveValidationErrorFor(x => x.Name);
}

[Fact]
public void Validate_WithNameAtMinimumLength_IsAccepted()
{
// BOUNDARY: exactly 3 characters must be accepted.
var request = ValidRequest();
request.Name = "Kdo";

_validator.TestValidate(request).ShouldNotHaveValidationErrorFor(x => x.Name);
}

[Theory]
[InlineData(0)]
[InlineData(-1)]
public void Validate_WithNonPositivePrice_HasErrorForPrice(decimal price)
{
var request = ValidRequest();
request.Price = price;

_validator.TestValidate(request)
.ShouldHaveValidationErrorFor(x => x.Price)
.WithErrorMessage("Fiyat pozitif olmalıdır.");
}

[Fact]
public void Validate_WithNegativeStock_HasErrorForStock()
{
var request = ValidRequest();
request.Stock = -1;

_validator.TestValidate(request).ShouldHaveValidationErrorFor(x => x.Stock);
}

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

[Fact]
public void Validate_WithInvalidEmail_HasErrorForNotificationEmail()
{
var request = ValidRequest();
request.NotificationEmail = "gecersiz-eposta";

_validator.TestValidate(request).ShouldHaveValidationErrorFor(x => x.NotificationEmail);
}

[Fact]
public void Validate_WithEmptyEmail_SkipsEmailRule()
{
// CONDITIONAL rule (When): if left empty, the e-mail rule does not run at all.
var request = ValidRequest();
request.NotificationEmail = null;

_validator.TestValidate(request).ShouldNotHaveValidationErrorFor(x => x.NotificationEmail);
}

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

[Fact]
public async Task ValidateAsync_WorksTheSameWay()
{
var request = ValidRequest();
request.Price = -5m;

var result = await _validator.TestValidateAsync(request);

result.ShouldHaveValidationErrorFor(x => x.Price);
}

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

  1. Test FluentValidation validators directly with TestValidate and TestValidateAsync; no controller and no mocks are needed.
  2. Start each test from a valid request and change one property, so each failure has one cause.
  3. Use ShouldHaveValidationErrorFor and ShouldNotHaveValidationErrorFor to check the exact property, and WithErrorMessage when the text matters.
  4. Test both sides of every boundary, such as two and three characters for a minimum length of three.
  5. A conditional When rule needs one test where it fires and one where it is skipped.