[英]Mock Generic Method with List of Objects
下面是我的接口有 2 个方法,一个接受单个 ICommand 对象,第二个接受 ICommand 对象列表。
我的第一种方法工作正常,但我的第二种方法没有通过 Mock 调用。 但在实际实现中它会被调用。
有人可以建议我缺少什么吗?
public interface ICommandBus
{
void Dispatch<TCommand>(TCommand command) where TCommand : ICommand;
void Dispatch<TCommand>(IList<TCommand> commands) where TCommand : ICommand;
}
[Test]
public void Test_Should_Work()
{
var commands = new List<ICommand>();
var mockDispatcher = Container.Instance.RegisterMock<ICommandBus>();
mockDispatcher.Setup(x => x.Dispatch(It.IsAny<ICommand>())).Callback<ICommand>(x => commands.Add(x));
mockDispatcher.Setup(x => x.Dispatch(It.IsAny<IList<ICommand>>())).Throws(new Exception("Some Error"));
var commandBus = SportsContainer.Resolve<ICommandBus>();
var commandslist = new List<UpdateCommand>()
{
new UpdateCommand(),
new UpdateCommand()
};
//first call is working
commandBus.Dispatch<UpdateCommand>(commandslist[0]);
//its not working. expected should throw an exception. but nothing is happening.
commandBus.Dispatch<UpdateCommand>(commandslist);
}
您的测试不会测试您的任何代码,它只是验证松散的模拟是否有效。 您不能对接口进行单元测试。
您的代码不会抛出,因为您使用了一个松散的模拟(默认),它什么都不做,只是为任何非设置调用返回 null。 您将List<UpdateCommand>
传递给使用It.IsAny<IList<ICommand>>()
设置的调用,该调用不匹配,因此您的.Throws()
永远不会执行,而是返回null
。
不要嘲笑被测类,因为那样你根本就没有测试任何东西。
所以你想测试你的实现:
var dispatcher = new YourDispatcher():
dispatcher.Dispatch<UpdateCommand>(commandslist[0]);
dispatcher.Dispatch<UpdateCommand>(commandslist);
我终于能够得到我需要的东西。 我需要具体定义 ICommand 的设置并且它有效。
[Test]
public void Test_Should_Work()
{
var commands = new List<ICommand>();
var mockDispatcher = Container.Instance.RegisterMock<ICommandBus>();
mockDispatcher.Setup(x => x.Dispatch(It.IsAny<IList<UpdateCommand>>())).Throws(new Exception("Some Error"));
var commandBus = SportsContainer.Resolve<ICommandBus>();
var commandslist = new List<UpdateScheduleCommand>()
{
new UpdateCommand(),
new UpdateCommand()
};
//first call is working
//commandBus.Dispatch<UpdateScheduleCommand>(commandslist[0]);
//its Working now.
commandBus.Dispatch(commandslist);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.