Skip to content
Michał Jankowski edited this page May 24, 2017 · 9 revisions

Welcome to the FluentValidation.Validators.UnitTestExtension wiki!

I believe that current content will help you to use this library.

Below you can find example of simple class:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int HeightInCentimeters { get; set; }
}

For this specific class the following validator has been created:

public class PersonValidator : AbstractValidator<Person>
{
  public PersonValidator()
  {
    RuleFor(person => person.FirstName).NotNull().NotEmpty().Length(0, 20);
    RuleFor(person => person.LastName).NotNull().NotEmpty().Length(0, 20);
    RuleFor(person => person.HeightInCentimeters).GreaterThan(0).LessThanOrEqualTo(250);
  }
}

As you can see I have defined some rules for each property. With this library your unit tests for validator will be very simple:

public class PersonValidatorTests_NewApproach
{
  // Act
  readonly PersonValidator personValidator = new PersonValidator();
 
  [Fact]
  public void Given_When_PersonValidatorConstructing_Then_3PropertiesShouldHaveRules()
  {
    // Assert
    personValidator.ShouldHaveRulesCount(3);
  }
 
  [Fact]
  public void Given_When_PersonValidatorConstructing_Then_RulesForFirstNameAreConfiguredCorrectly()
  {
    // Assert
    personValidator.ShouldHaveRules(x => x.FirstName,
      BaseVerifiersSetComposer.Build()
        .AddPropertyValidatorVerifier<NotNullValidator>()
        .AddPropertyValidatorVerifier<NotEmptyValidator>()
        .AddPropertyValidatorVerifier<LengthValidator>(0, 20)
        .Create());
  }
 
  [Fact]
  public void Given_When_PersonValidatorConstructing_Then_RulesForLastNameAreConfiguredCorrectly()
  {
    // Assert
    personValidator.ShouldHaveRules(x => x.LastName,
      BaseVerifiersSetComposer.Build()
        .AddPropertyValidatorVerifier<NotNullValidator>()
        .AddPropertyValidatorVerifier<NotEmptyValidator>()
        .AddPropertyValidatorVerifier<LengthValidator>(0, 20)
        .Create());
  }
 
  [Fact]
  public void Given_When_PersonValidatorConstructing_Then_RulesForHeightAreConfiguredCorrectly()
  {
    // Assert
    personValidator.ShouldHaveRules(x => x.HeightInCentimeters,
      BaseVerifiersSetComposer.Build()
        .AddPropertyValidatorVerifier<GreaterThanValidator>(0)
        .AddPropertyValidatorVerifier<LessThanOrEqualValidator>(250)
        .Create());
  }
}

As you can see provided code will test two things:

  • number of properties that are being checked by FluentValidation rules
  • rules configuration.

Please note that order of rules definition is also verified by test.

You can’t perform that action at this time.