Mocking MediatR 3 with Moq

前端 未结 1 717
天涯浪人
天涯浪人 2021-02-13 03:11

We\'ve recently started using MediatR to allow us to de-clutter controller actions as we re-factor a large customer facing portal and convert it all to C#. As part of this we ar

相关标签:
1条回答
  • 2021-02-13 03:32

    You need to handle the await of the async operation of the Send methods as they return tasks.

    /// <summary>
    /// Asynchronously send a request to a single handler
    /// </summary>
    /// <typeparam name="TResponse">Response type</typeparam>
    /// <param name="request">Request object</param>
    /// <param name="cancellationToken">Optional cancellation token</param>
    /// <returns>A task that represents the send operation. The task result contains the handler response</returns>
    Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default(CancellationToken));
    
    /// <summary>
    /// Asynchronously send a request to a single handler without expecting a response
    /// </summary>
    /// <param name="request">Request object</param>
    /// <param name="cancellationToken">Optional cancellation token</param>
    /// <returns>A task that represents the send operation.</returns>
    Task Send(IRequest request, CancellationToken cancellationToken = default(CancellationToken));
    

    That means you need to have the mock return a task to allow the async process to continue the flow

    mediator
        .Setup(m => m.Send(It.IsAny<TransferNotificationCommand>(), It.IsAny<CancellationToken>()))
        .ReturnsAsync(new Notification()) //<-- return Task to allow await to continue
        .Verifiable("Notification was not sent.");
    
    //...other code removed for brevity
    
    mediator.Verify(x => x.Send(It.IsAny<CreateIsaTransferNotificationCommand>(), It.IsAny<CancellationToken>()), Times.Once());
    
    0 讨论(0)
提交回复
热议问题