Validator tests standard¶
This page sets the rules for unit tests of validators in ConnectSoft services and libraries. It is written for engineers who add or review validators and their tests. How validation is wired into services is explained in Validation.
ConnectSoft code has two kinds of validators:
- Input validators derive from FluentValidation
AbstractValidator<T>. Domain services call them withValidateAndThrowAsyncbefore doing any work. - Options validators implement
IValidateOptions<TOptions>. The host calls them when options are bound at start-up.
A validator is the last line of defence before data reaches the domain model and the database. A rule that is never tested can be removed or inverted by a refactoring without any test failing.
Rules¶
CS-VAL-001: Every validator has a dedicated unit test class¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
Validators are usually tested only indirectly, through a domain service test that passes one valid input. That proves the happy path and nothing else. A dedicated test class makes each rule visible and keeps it from being lost in a refactoring.
Do¶
- Give every
AbstractValidator<T>and everyIValidateOptions<T>implementation its own test class. - Name the class
<ValidatorName>UnitTests, for exampleCreateOrderInputValidatorUnitTests. - Put the class in the unit test project that mirrors the validator's project, in the same folder structure.
Don't¶
- Rely on domain service tests or acceptance tests as the only tests of a validator.
- Test several validators in one test class.
Example¶
Orders.DomainModel.Impl/Validators/CreateOrderInputValidator.cs
Orders.UnitTests/DomainModel/Validators/CreateOrderInputValidatorUnitTests.cs
How to check¶
- For each new or changed validator in the change, a
<ValidatorName>UnitTestsclass exists or is added. - Options validators added by a template have tests in the template's unit test project.
CS-VAL-002: Test the valid input and every rule¶
Severity: major · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
A test that only checks a valid input passes even when every rule has been deleted. A test that only checks invalid inputs passes even when the validator rejects everything. Both directions are needed, and conditional rules have two branches that can each break.
Do¶
- Write one test that a fully valid input passes.
- Write at least one failing test for each rule in the validator.
- For a rule inside
When(...)orUnless(...), test both branches: the condition is true and the rule fails, and the condition is false and the same value passes. - For a range or length rule, test the value just inside and just outside the boundary.
Don't¶
- Test only that some invalid input fails.
- Leave a rule without a test because it "looks obvious".
Example¶
[TestMethod]
public async Task ValidateAsyncPassesForValidInput()
{
// Arrange
var validator = new CreateOrderInputValidator();
var input = GetValidInput();
// Act
var result = await validator.ValidateAsync(input).ConfigureAwait(false);
// Assert
Assert.IsTrue(result.IsValid);
}
[TestMethod]
public async Task ValidateAsyncFailsWhenDeliveryDateIsMissingForExpressOrder()
{
// Arrange
var validator = new CreateOrderInputValidator();
var input = GetValidInput();
input.IsExpress = true;
input.DeliveryDate = null;
// Act
var result = await validator.ValidateAsync(input).ConfigureAwait(false);
// Assert
Assert.IsFalse(result.IsValid);
Assert.AreEqual(nameof(CreateOrderInput.DeliveryDate), result.Errors.Single().PropertyName);
}
[TestMethod]
public async Task ValidateAsyncPassesWhenDeliveryDateIsMissingForStandardOrder()
{
// Arrange
var validator = new CreateOrderInputValidator();
var input = GetValidInput();
input.IsExpress = false;
input.DeliveryDate = null;
// Act
var result = await validator.ValidateAsync(input).ConfigureAwait(false);
// Assert
Assert.IsTrue(result.IsValid);
}
How to check¶
- Count the
RuleForandRuleForEachchains, and eachWhenorUnlessblock, in the validator. Each has at least one failing test, and each condition has a test for its other branch. - A valid-input test exists.
CS-VAL-003: Reject Guid.Empty explicitly on nullable identifiers¶
Severity: major · Applies to: service, library · Enforced by: manual · Status: active
Why¶
FluentValidation NotEmpty() on a Guid? property checks only that the value is not null. It accepts Guid.Empty, so an input with an all-zero identifier passes validation and reaches the domain model. For a non-nullable Guid, NotEmpty() does reject Guid.Empty, which makes the nullable case easy to miss.
Do¶
- On a
Guid?identifier that is required, use a rule that rejects bothnullandGuid.Empty, such asMust(id => id.HasValue && id.Value != Guid.Empty). - Add a test that passes
Guid.Emptyand expects the rule to fail, next to the test fornull.
Don't¶
- Use
NotEmpty()orNotNull()alone on a requiredGuid?identifier.
Example¶
// Validator
this.RuleFor(input => input.CustomerId)
.Must(id => id.HasValue && id.Value != Guid.Empty)
.WithMessage("CustomerId is required.");
// Test
[TestMethod]
public async Task ValidateAsyncFailsWhenCustomerIdIsEmptyGuid()
{
// Arrange
var validator = new CreateOrderInputValidator();
var input = GetValidInput();
input.CustomerId = Guid.Empty;
// Act
var result = await validator.ValidateAsync(input).ConfigureAwait(false);
// Assert
Assert.IsFalse(result.IsValid);
}
How to check¶
- Search the validator for
NotEmpty()orNotNull()on a property declared asGuid?. - Check that the tests include a
Guid.Emptycase for every requiredGuid?identifier.
CS-VAL-004: Build test inputs from a valid baseline¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
When each test builds its input from scratch, a failing test may fail for a reason other than the one it names, because another property is also invalid. Starting from one valid input and changing one property makes each test prove exactly one rule.
Do¶
- Add a private static factory method, such as
GetValidInput(), that returns a fully valid input. - In each failing test, start from the baseline and change only the property under test.
- When the validator gains a rule, update the baseline so it stays valid.
Don't¶
- Build a separate input object in each test.
- Change more than one property in a test that names a single rule.
Example¶
private static CreateOrderInput GetValidInput()
{
return new CreateOrderInput
{
OrderId = Guid.NewGuid(),
CustomerId = Guid.NewGuid(),
IsExpress = false,
DeliveryDate = null,
};
}
How to check¶
- The test class has one valid baseline factory.
- Each failing test changes one property of the baseline.
CS-VAL-005: Assert the specific failure¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
A test that asserts only IsValid == false keeps passing when the rule it names is removed, as long as any other rule fails. Asserting the property, error code or exception type ties the test to the rule.
Do¶
- For
ValidateAsync, assert the failing property name or error code. - For a validator whose rules throw domain exceptions, assert the exact exception type with
Assert.ThrowsExactlyAsync<TException>. - Use MSTest
Assert, as set in ADR-0106.
Don't¶
- Assert only
IsValid == falseor only that some exception was thrown. - Use
Assert.ThrowsAsync<TException>when the rule throws a specific type, because it also accepts derived exception types.
Example¶
[TestMethod]
public async Task ValidateAndThrowAsyncThrowsOrderIdRequiredExceptionWhenOrderIdIsEmpty()
{
// Arrange
var validator = new CreateOrderInputValidator();
var input = GetValidInput();
input.OrderId = Guid.Empty;
// Act and assert
await Assert.ThrowsExactlyAsync<OrderIdRequiredException>(
() => validator.ValidateAndThrowAsync(input)).ConfigureAwait(false);
}
How to check¶
- Each failing test asserts a property name, an error code or an exact exception type.
- Search validator tests for
Assert.ThrowsAsync<. Where the rule throws a specific type, the test usesAssert.ThrowsExactlyAsync<instead.
Related¶
- Validation explains how validation is wired into services.
- Engineering standards describes how rules are written and applied.
- ADR-0105: Code convention baseline sets the test naming convention.
- ADR-0106: Default stack positioning sets MSTest and its assertions.