I am using fluentvalidation as follows:
public class ProjectValidator : AbstractValidator<Project>
{
public ProjectValidator()
{
RuleFor(project => project.Name).NotEmpty().WithMessage("Project name cannot be empty.");
}
}
in some service:
IValidator<Project> _projectValidator;
_projectValidator.ValidateAndThrow(project);
part of the integration test:
var validationException = Assert.Throws<ValidationException>(() => projectRepository.SaveOrUpdate(project));
Assert.That(validationException.Message, Is.EqualTo("Project name cannot be empty."));
This obviously does not work as validationException potentially contains many errors. Even if it only contains one error the string looks like this:
Validation failed: -- Project name cannot be empty.
How would you check that the validation resulted/contains the specified validation message?:
Project name cannot be empty.
You can make assertion against validationException.Errors collection:
Assert.IsNotNull(validationException.Errors.SingleOrDefault(error => error.ErrorMessage.Equals("Project name cannot be empty.")));
Or, you can do the same using FluentAssertions:
validationException.Errors.Should().Contain(error => error.ErrorMessage.Equals("Project name cannot be empty."));