【发布时间】:2020-03-14 22:34:29
【问题描述】:
我正在使用 FluentValidation 和 MediatR PipelineBehavior 来验证 CQRS 请求。我应该如何在单元测试中测试这种行为?
-
使用 FluentValidation 的 test extensions,我只测试规则。
[Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Should_have_error_when_name_is_empty(string recipeName) { validator.ShouldHaveValidationErrorFor(recipe => recipe.Name, recipeName); } -
在单元测试中手动验证请求
[Theory] [InlineData("")] [InlineData(" ")] public async Task Should_not_create_recipe_when_name_is_empty(string recipeName) { var createRecipeCommand = new CreateRecipeCommand { Name = recipeName, }; var validator = new CreateRecipeCommandValidator(); var validationResult = validator.Validate(createRecipeCommand); validationResult.Errors.Should().BeEmpty(); } -
初始化管道行为
[Theory] [InlineData("")] [InlineData(" ")] public async Task Should_not_create_recipe_when_name_is_empty(string recipeName) { var createRecipeCommand = new CreateRecipeCommand { Name = recipeName }; var createRecipeCommandHandler = new CreateRecipeCommand.Handler(_context); var validationBehavior = new ValidationBehavior<CreateRecipeCommand, MediatR.Unit>(new List<CreateRecipeCommandValidator>() { new CreateRecipeCommandValidator() }); await Assert.ThrowsAsync<Application.Common.Exceptions.ValidationException>(() => validationBehavior.Handle(createRecipeCommand, CancellationToken.None, () => { return createRecipeCommandHandler.Handle(createRecipeCommand, CancellationToken.None); }) ); }
或者我应该使用更多这些?
ValidationBehavior 类:
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public RequestValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var context = new ValidationContext(request);
var failures = _validators
.Select(v => v.Validate(context))
.SelectMany(result => result.Errors)
.Where(f => f != null)
.ToList();
if (failures.Count != 0)
{
throw new ValidationException(failures);
}
return next();
}
}
【问题讨论】:
标签: c# unit-testing cqrs fluentvalidation mediatr