如何从另一个命令处理程序模拟命令处理程序调用

时间:2014-04-07 02:18:16

标签: c# unit-testing

我有 UpdateHandler ,我想测试它是否有效。但是,我有一个问题,我不知道如何模仿 CanChangeHandler

我为这个处理程序创建了另一个测试。在 UpdateHandler 中我希望得到 canChangeResponse ,其中Can为true / false,并根据我想测试 UpdateHandler canChangeResponse < / strong>是 null

我尝试了几种不同的方法来模拟 commandDispather CanChangeHandler , 但它还没有奏效。

是否有人遇到类似问题?

我的代码如下(我只提供相关代码来说明问题所在。)

public UpdateHandler(ICommandDispatcher commandDispatcher)
{
    _commandDispatcher = commandDispatcher;
}

public override SimpleResponse Handle(CreateScheduleCommand command)
{
    try
    {
        var canChangeResponse = _commandDispatcher.Get<CanResponse>(
            new CanChangeCommand(command.Id));

        if (!canChangeResponse.Can)
        {
            return new SimpleResponse(canChangeResponse.Why);
        }

        //update code comes here and I want to test this

        return new SimpleResponse();
    }
    catch (Exception e)
    {
        _log.CommandError(command, e);
        return new SimpleResponse(Resources.GeneralFailure);
    }
}

测试设置:

_container = new WindsorContainer();
new ContainerConfiguration(_container).Apply();

_container.Install(new MongoRepositoriesInstaller(_mongoConnectionString, typeof(User).Assembly));

_container.Install(new CommandHandlersInstaller());
//new CommandProcessorConfiguration(_container).Apply();

var commandDispatcher = new Mock<ICommandDispatcher>();
commandDispatcher.Setup(x => x.Get<CanResponse>(new CanUpdateCommand())).Returns(new CanResponse { Can = true });

var canUpdateHandler = new Mock<ICommandHandler<CanUpdateCommand, CanResponse>>();
canUpdateHandler.Setup(x => x.Handle(new CanUpdateCommand())).Returns(new CanResponse { Can = true });
_container.Register(Component.For<ICommandHandler<CanUpdateCommand, CanResponse>>().Instance(canUpdateHandler.Object));

测试:

[Ignore]
[Test]
public void Update()
{
    // Arrange

    var commandDispatcher = Container.Resolve<ICommandDispatcher>();
    var handler = new UpdateHandler(commandDispatcher);

    // Act

    var response = handler.Handle(new UpdateCommand());

    // Assert

    Assert.IsFalse(response.HasErrors);
}

1 个答案:

答案 0 :(得分:0)

不确定为什么要在单元测试中使用IOC容器,这会增加一些额外的复杂性来处理。您可以在ICommandDispature上轻松设置存根。

        var stubCommandDispatcher = new Mock<ICommandDispatcher>();
        stubCommandDispatcher.Setup(x => x.Get<CanResponse>
            (It.IsAny<CanChangeCommand>()))
            .Returns(new CanResponse() {Can = true});

        var stubScheduleCommand = new Mock<CreateScheduleCommand>();
        var sut = new UpdateHandler(stubCommandDispatcher.Object);

        var r = sut.Handle(stubScheduleCommand.Object);