1
我有UpdateHandler我想測試它是否工作或沒有。但是,我有一個問題,我不知道如何嘲笑CanChangeHandler。如何從另一個命令處理程序模擬命令處理程序調用
我爲這個處理程序創建了另一個測試。在UpdateHandler我想canChangeResponse與CAN是真/假,並基於該我想測試UpdateHandler是canChangeResponse是空。
我已經嘗試了幾種不同的方式來嘲笑兩者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);
}
謝謝,這很有幫助。 此外,我發現下面的行也可以幫助。 commandDispatcher.SetReturnsDefault(new CanResponse {Can = true}); –
nikola