我试图嘲讽通用方法,并且它不按预期方式工作。Moq - 嘲讽通用方法的正确设置
我有这样的服务定义
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);
我应该如何设置起订量,即使在这种情况下返回正确的处理程序?
不,我没有,因为我想测试我的CommandBus实现,所以我不能嘲笑它。 –