我正在使用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();
}
}
我认为您所有的示例都很好。如果他们涵盖了您的代码,那么他们将提供您所需要的。
我要描述的是一种稍微不同的方法。我将提供一些背景。
我们在Core(2.1)中使用Mediatr,FluentValidation。我们包装了Mediatr实现,这是我们要做的:
我们有一个通用的pre-handler(只为每个处理程序运行),并为传入的命令/查询寻找FluentValdator。如果找不到匹配的项,它就会继续传递。如果这样做,它将运行它,如果验证失败,它将获取结果并在响应中返回带有我们标准验证套的BadRequest。我们还具有在业务处理程序中获取验证工厂的功能,因此可以手动运行它们。对于开发人员来说意味着更多的工作!
因此,为了进行测试,我们使用Microsoft.AspNetCore.TestHost创建一个我们的测试可以命中的终结点。这样做的好处是测试了整个Mediatr管道(包括验证)。
所以我们有这种事情:
var builder = WebHost.CreateDefaultBuilder()
.UseStartup<TStartup>()
.UseEnvironment(EnvironmentName.Development)
.ConfigureTestServices(
services =>
{
services.AddTransient((a) => this.SomeMockService.Object);
});
this.Server = new TestServer(builder);
this.Services = this.Server.Host.Services;
this.Client = this.Server.CreateClient();
this.Client.BaseAddress = new Uri("http://localhost");
这定义了我们的测试服务器将模拟的东西(可能是下游的http类等)和其他各种东西。
然后我们可以达到实际的控制器端点。因此,我们测试是否已注册了所有内容以及整个pipleline。
看起来像这样(一个例子,只是为了测试一点验证):
public SomeControllerTests(TestServerFixture testServerFixture):基础(testServerFixture){}
[Fact]
public async Task SomeController_Titles_Fails_With_Expected_Validation_Error()
{
// Setup whatever you need to do to make it fail....
var response = await this.GetAsync("/somedata/titles");
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
var responseAsString = await response.Content.ReadAsStringAsync();
var actualResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ValidationStuff);
actualResponse.Should().NotBeNull();
actualResponse.Should().HaveCount(1);
actualResponse.[0].Message.Should().Be("A message");
}
正如我说的,我认为您的任何选择都会满足您的需求。如果我必须选择单元测试(这只是个人选择),我会选择2):-)
我们发现,当您的处理程序pipleline非常简单时,更多的系统/集成测试路线会非常有效。当它们变得更加复杂时(我们有一个带有大约12个处理程序,加上大约6个通过使用包装器获得的处理程序),我们将它们与通常与您对2或3完成的操作相匹配的单个处理程序测试一起使用。
有关系统/集成测试的更多信息,此链接应有帮助。https://fullstackmark.com/post/20/painless-integration-testing-with-aspnet-core-web-api
我希望这有助于或至少给您带来一些思考:-)