Assuming a class with a custom validator, similar to the following:
public record FeedbackCreateRequest
{
public string Url { get; set; } = null!;
public FeedbackResponse Response { get; set; } // An enum consisting of 3 options
public string? Context { get; set; }
public class Validator : AbstractValidator<FeedbackCreateRequest>
{
public Validator()
{
RuleFor(request => request.Url)
.NotEmpty();
RuleFor(request => request.Response)
.IsInEnum();
RuleFor(request => request.Context)
.MaximumLength(250);
}
}
}
You can easily verify the request object is being validated as you expect by instantiating the validator and calling ShouldHaveValidationErrorFor
:
[Fact]
public async Task FeedbackCreateRequestValidator_InvalidFields_IncludesRelevantErrors()
{
// Arrange
var validator = new FeedbackCreateRequest.Validator();
var request = new FeedbackCreateRequest
{
Response = (FeedbackResponse)5,
Context = new string('a', 251),
};
// Act
var result = await validator.TestValidateAsync(request);
// Assert
Assert.Equal(3, result.Errors.Count);
result.ShouldHaveValidationErrorFor(feedback => feedback.Url);
result.ShouldHaveValidationErrorFor(feedback => feedback.Response);
result.ShouldHaveValidationErrorFor(feedback => feedback.Context);
}