I am trying to mock a generic method and it doesn't work as expected.
I have this service definition
public interface ICommandHandlerFactory {
ICommandHandler<T> GetHandler<T>() where T : ICommand;
}
and this Moq setup
var handler = new TestCommandHandler();
var handlerFactory = Mock.Of<ICommandHandlerFactory>(o =>
o.GetHandler<TestCommand>() == handler);
If I call GetHandler
method on the mock with the specific type e.g. GetHandler<TestCommand>
everything is working as expected and it returns instance of the TestCommandHandler
class.
But if the mock is injected to another generic class
public class CommandBus {
private ICommandHandlerFactory _handlerFactory;
public ICommandHandler GetHandler<T>(T command) where T : ICommand {
return _handlerFactory.GetHandler<T>();
}
}
the following piece of code return null
var command = new TestCommand();
return commandBus.GetHandler(command);
How should I setup Moq to return correct handler even in this case?