【问题标题】:Moq - Correct setup for mocking generic methodMoq - 模拟通用方法的正确设置
【发布时间】:2014-12-23 18:28:00
【问题描述】:

我正在尝试模拟一个泛型方法,但它没有按预期工作。

我有这个服务定义

public interface ICommandHandlerFactory {
    ICommandHandler<T> GetHandler<T>() where T : ICommand;
}

还有这个起订量设置

var handler = new TestCommandHandler();
var handlerFactory = Mock.Of<ICommandHandlerFactory>(o => 
     o.GetHandler<TestCommand>() == handler);

如果我在具有特定类型的模拟上调用 GetHandler 方法,例如GetHandler&lt;TestCommand&gt; 一切都按预期工作,它返回 TestCommandHandler 类的实例。

但是如果mock被注入到另一个泛型类中

public class CommandBus {
    private ICommandHandlerFactory _handlerFactory;

    public ICommandHandler GetHandler<T>(T command) where T : ICommand {
        return _handlerFactory.GetHandler<T>();
    }
}

以下代码返回null

var command = new TestCommand();
return commandBus.GetHandler(command);

即使在这种情况下,我应该如何设置 Moq 以返回正确的处理程序?

【问题讨论】:

标签: c# generics moq


【解决方案1】:

你尝试过这样的事情吗?

var handler = new TestCommandHandler();
Mock<ICommandHandlerFactory> handlerFactory = new Mock<ICommandHandlerFactory>();
handlerFactory.Setup(x => x.GetHandler<TestCommand>()).Returns(handler);

Mock<CommandBus> commandBus = new Mock<CommandBus>();
commandBus.Setup(x => x.GetHandler<TestCommand>(It.IsAny<TestCommand>())).Returns(handler);

【讨论】:

  • 不,我没有,因为我正在尝试测试我的 CommandBus 实现,所以我无法模拟它。
【解决方案2】:

原始代码有效,在初始化 TestCommand 类的辅助方法中存在问题,并且未包含在问题中。

命令在初始化时被强制转换为它们的基本接口 (ICommand)。模拟设置为返回 TestCommand 类型的处理程序,但使用 ICommand 类型调用 - 这就是它返回 null 的原因

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2018-07-16
    • 2010-11-12
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多