Question

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.

Was it helpful?

Solution

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."));

OTHER TIPS

FluentValidations also includes a clean way to do this using FluentActions.

FluentActions.Invoking(() => projectRepository.SaveOrUpdate(project))
.Should()
.Throw<ValidationException>()
.WithMessage("Project name cannot be empty.");

More examples here: https://fluentassertions.com/exceptions/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top