最小起订量 - 模拟通用方法的正确设置

本文关键字:方法 设置 模拟 | 更新日期: 2023-09-27 18:34:56

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

我有此服务定义

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<TestCommand>一切都按预期工作,它返回 TestCommandHandler 类的实例。

但是如果将模拟注入到另一个泛型类中

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 以返回正确的处理程序?

最小起订量 - 模拟通用方法的正确设置

你试过这样的事情吗?

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);

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

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