我正在使用FluentValidation验证请求。如果验证失败,则不应调用UseCaseHandler。在UseCaseHandler中,我使用IRepository,这将检查以查看UseCaseHandler是否被调用。

请求验证器

 public class MyValidator: AbstractValidator<Request>
 {
     public MyValidator()
     {
         RuleFor(rq=> rq)
              .Cascade(CascadeMode.Continue);
         RuleFor(rq=> rq)
            .Must(property => property.id != default(Guid))
            .WithMessage(message => $"invalid id.")
            .WithName(member => nameof(member.Id));

      }
 }


这是测试

[Fact]
public async Task Test()
{
     Mock<IUnitOfWork> uowMock = new Mock<IUnitOfWork>();
     Mock<IRepository> repositoryMock = new Mock<IRepository>(MockBehavior.Strict);
     Mock<IValidator<Request>> validatorMock = new Mock<IValidator<Request>>(MockBehavior.Strict);

     var request = new Request
     {
        Id = Guid.NewGuid()
     };

     validatorMock
         .Setup(validator => validator.Validate(request))
         .Returns(new ValidationResult());

     repositoryMock
          .Setup(repo => repo.SaveAsync(It.IsAny<object>()))
          .Returns(Task.CompletedTask);

     var sut = new UseCase(uowMock.Object, repositoryMock.Object, validatorMock.Object);


     Func<Task> act = () => sut.UseCaseHandler(request);


     await act.Should().NotThrowAsync();
     repositoryMock.Verify(repo => repo.SaveAsync(It.IsAny<object>()), Times.Once);
 }


我正在寻找编写可以检查流程的测试。

如果验证失败,则测试将失败,并且不应调用SaveAsync。

如果验证成功,则测试也应成功,并且SaveAsync应该被调用一次。

编写测试的方式是什么?

更新

这是用例类定义。

UseCaseHandlerProxy是充当代理的基本抽象类

public class UseCase : UseCaseHandlerProxy<Request, Response>
{
    private readonly IRepository _repository;


    public UseCase(IUnitOfWork unitOfWork, IRepository repository, IValidator<Request> validator)
        : base(unitOfWork, validator)
    {
        _repository = repository
    }

    public override async Task<Response> UseCaseHandler(Request request)
    {
        Order order = new Order();

        order.Create();

        await _repository.SaveAsync(order);

        return new Response(order.Id);
    }
}


这是Request类的定义

class Request
{
    public Guid Id { get; set; }
}


Te响应仅返回相同的ID

代理类

public abstract class UseCaseHandlerProxy<TRequest, TResponse> : IUseCaseHandler<TRequest, TResponse>
    where TRequest : IRequest
    where TResponse : Response
{
    private IValidator<TRequest> Validator { get; }
    protected internal IUnitOfWork UnitOfWork { get; }


    public UseCaseHandlerProxy(IUnitOfWork unitOfWork, IValidator<TRequest> validator)
    {
        Validator = validator;
        UnitOfWork = unitOfWork;
    }

    async Task<TResponse> IUseCaseHandler<TRequest, TResponse>.HandleAsync(TRequest request)
    {
        ValidationResult validationResult = await Validator.ValidateAsync(request);

        TResponse response;

        if (!validationResult.IsValid)
        {
            response = (TResponse)System.Activator.CreateInstance(typeof(TResponse));

            validationResult.Errors.ToList().ForEach(error => response.AddError(error.PropertyName, error.ErrorMessage));

            return response;
        }

        response = await UseCaseHandler(request);

        return response;
    }

    public abstract Task<TResponse> UseCaseHandler(TRequest request);
}

最佳答案

给定您要测试的流程,我会说您正在调用错误的成员。

sut强制转换为IUseCaseHandler<TRequest, TResponse>以访问HandleAsync,这是所需的流程。

例如,以下内容验证了,如果没有验证错误,则存储库将调用保存。

[Fact]
public async Task UseCase_Should_Save() {
    //Arrange
    Mock<IUnitOfWork> uowMock = new Mock<IUnitOfWork>();
    Mock<IRepository> repositoryMock = new Mock<IRepository>(MockBehavior.Strict);
    Mock<IValidator<Request>> validatorMock = new Mock<IValidator<Request>>(MockBehavior.Strict);

    var request = new Request {
        Id = Guid.NewGuid()
    };

    validatorMock
        .Setup(validator => validator.ValidateAsync(request, It.IsAny<CancellationToken>()))
        .ReturnsAsync(new ValidationResult());

    repositoryMock
         .Setup(repo => repo.SaveAsync(It.IsAny<object>()))
         .Returns(Task.FromResult((object)null));

    var sut = new UseCase(uowMock.Object, repositoryMock.Object, validatorMock.Object) as IUseCaseHandler<Request, Response>;

    //Act
    Func<Task> act = () => sut.HandleAsync(request);

    //Assert
    await act.Should().NotThrowAsync();
    repositoryMock.Verify(repo => repo.SaveAsync(It.IsAny<object>()), Times.Once);
}


以下内容验证如果有错误,则存储库不会保存

[Fact]
public async Task UseCase_Should_Not_Save() {
    //Arrange
    var uowMock = new Mock<IUnitOfWork>();
    var repositoryMock = Mock.Of<IRepository>();
    var validatorMock = new Mock<IValidator<Request>>(MockBehavior.Strict);

    var request = new Request {
        Id = Guid.NewGuid()
    };

    var result = new ValidationResult();
    result.Errors.Add(new ValidationFailure("SomeProperty", "SomeError"));

    validatorMock
        .Setup(validator => validator.ValidateAsync(request, It.IsAny<CancellationToken>()))
        .ReturnsAsync(result);

    var sut = new UseCase(uowMock.Object, repositoryMock, validatorMock.Object) as IUseCaseHandler<Request, Response>;

    //Act
    Func<Task> act = () => sut.HandleAsync(request);

    //Assert
    await act.Should().NotThrowAsync();
    Mock.Get(repositoryMock).Verify(repo => repo.SaveAsync(It.IsAny<object>()), Times.Never);
}

关于c# - Moq:使用FluentValidation运行流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53710685/

10-13 21:27