2014-04-07 89 views
1

我有UpdateHandler我想測試它是否工作或沒有。但是,我有一個問題,我不知道如何嘲笑CanChangeHandler如何從另一個命令處理程序模擬命令處理程序調用

我爲這個處理程序創建了另一個測試。在UpdateHandler我想canChangeResponse與CAN是真/假,並基於該我想測試UpdateHandlercanChangeResponse

我已經嘗試了幾種不同的方式來嘲笑兩者commandDispatherCanChangeHandler, 但它只是沒有奏效。

有沒有人有類似問題的經驗?

我的代碼在下面(我只是放了相關的代碼來顯示問題)。

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); 
} 

回答

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); 
+0

謝謝,這很有幫助。 此外,我發現下面的行也可以幫助。 commandDispatcher.SetReturnsDefault (new CanResponse {Can = true}); – nikola

相關問題