Mocking MediatR 3 with Moq

前端 未结 1 718
天涯浪人
天涯浪人 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.

    /// 
    /// Asynchronously send a request to a single handler
    /// 
    /// Response type
    /// Request object
    /// Optional cancellation token
    /// A task that represents the send operation. The task result contains the handler response
    Task Send(IRequest request, CancellationToken cancellationToken = default(CancellationToken));
    
    /// 
    /// Asynchronously send a request to a single handler without expecting a response
    /// 
    /// Request object
    /// Optional cancellation token
    /// A task that represents the send operation.
    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(), It.IsAny()))
        .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(), It.IsAny()), Times.Once());
    

    0 讨论(0)
提交回复
热议问题