【问题标题】:Mock handler with parameter Mediatr and Moq带有参数 Mediatr 和 Moq 的模拟处理程序
【发布时间】:2020-03-23 09:16:11
【问题描述】:

我正在尝试使用 Moq 模拟处理程序。此处理程序采用 bool 类型的参数来过滤掉活跃客户和非活跃客户。

处理程序用于我的服务:

    public async Task<IEnumerable<CustomerDto>> GetCustomers(bool active)
    {
        return _mapper.Map<IEnumerable<CustomerDto>>(await _mediatr.Send(new GetCustomersQuery { Active = active }));
    }

我的处理程序如下所示:

public class GetCustomersHandler : IRequestHandler<GetCustomersQuery, IEnumerable<Customer>>
{

    private readonly ICustomersRepository _repository;

    public GetCustomersHandler(ICustomersRepository repository)
    {
        _repository = repository;
    }

    public async Task<IEnumerable<Customer>> Handle(GetCustomersQuery request, CancellationToken cancellationToken)
    {
        return await _repository.GetCustomers(request.Active);
    }
}

我的测试:

    [Fact]
    public async Task CustomersService_GetCustomers_ActiveReturnsOnlyActiveCustomers()
    {
        var result = await _service.GetCustomers(true);

        // asserts to test result
    }

我的模拟代码:

        var mockMediatr = new Mock<IMediator>();
        mockMediatr.Setup(m => m.Send(It.IsAny<GetBlockedCustomersAndGroupsQuery>(), It.IsAny<CancellationToken>()))
            .Returns(async (bool active) => 
                await _getBlockedCustomersAndGroupsHandler.Handle(new GetBlockedCustomersAndGroupsQuery { Active = active }, new CancellationToken())); ---> How can I pass my bool parameter here?

编辑: 我的测试中没有中介的模拟代码(用于重用)。我希望能够测试通过 true 和 false 的两种情况。如果我像上面提到的那样尝试它,我会收到此错误:“无效的回调。在具有 2 个参数的方法上设置无法调用具有不同数量参数 (1) 的回调”。

我可以在测试代码中模拟中介并通过:

mockMediatr.Setup(m => m.Send(It.IsAny<GetBlockedCustomersAndGroupsQuery>(), It.IsAny<CancellationToken>()))
            .Returns(async () => 
                await _getBlockedCustomersAndGroupsHandler.Handle(new GetBlockedCustomersAndGroupsQuery { Active = true }, new CancellationToken()));

但是在这里我无法在第二个测试中重用它(Active = false),并且我有一些重复的代码。有没有办法做到这一点,还是我需要将模拟代码放在测试代码中?

【问题讨论】:

  • 你应该表达你的问题:你期望什么,发生了什么?并解释您为将两者结合在一起所做的工作。
  • @Rico-E 我希望这能澄清我想知道的:)
  • 好多了,谢谢
  • 除了存储库之外,您没有尝试模拟任何内容吗?
  • 想象一下,当您决定摆脱 MediaR 时,您需要做出哪些改变。 (你可能会在一段时间后;))

标签: c# moq xunit cqrs mediator


【解决方案1】:

我找到了如何访问传递的数据。

mockMediatr.Setup(m => m.Send(It.IsAny(), It.IsAny())) .Returns(async (GetBlockedCustomersAndGroupsQuery q, CancellationToken token) => await _getBlockedCustomersAndGroupsHandler.Handle(new GetBlockedCustomersAndGroupsQuery { Active = q.Active}, token));

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2016-06-16
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2020-01-24
    • 2019-07-02
    相关资源
    最近更新 更多