FluentValidation Integration Test and Exception Report

I use 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, since a validationException potentially contains many errors. Even if it contains only one error, the line looks like this:

Verification failed: - The project name cannot be empty.

How do you verify that the verification message indicated / indicated the verification message?

Project name cannot be empty.

+4
source share
1 answer

You can make a statement 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.")); 
+3
source

Source: https://habr.com/ru/post/1493000/


All Articles