C# Moq-模拟通用方法的正确设置

C# Moq-模拟通用方法的正确设置,c#,generics,moq,C#,Generics,Moq,我试图模拟一个泛型方法,但它没有按预期工作 我有这个服务定义 public interface ICommandHandlerFactory { ICommandHandler<T> GetHandler<T>() where T : ICommand; } 下面的代码返回null var command = new TestCommand(); return commandBus.GetHandler(command); 即使在这种情况下,我应该如何设置Mo

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

我有这个服务定义

public interface ICommandHandlerFactory {
    ICommandHandler<T> GetHandler<T>() where T : ICommand;
}
下面的代码返回
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);
var handler=newtestcommandhandler();
Mock handlerFactory=新Mock();
Setup(x=>x.GetHandler()).Returns(handler);
Mock commandBus=new Mock();
Setup(x=>x.GetHandler(It.IsAny()).Returns(handler);

原始代码正常工作,初始化
TestCommand
类的帮助器方法中有一个问题,该问题不包括在内


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

不,我没有返回,因为我试图测试我的CommandBus实现,所以我无法模拟它。也许这个问题也可以帮助:
var command = new TestCommand();
return commandBus.GetHandler(command);
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);