2012-10-18 23 views
3

我有以下的測試案例:使用起訂量來驗證與正確的命令參數一個CommandHandler方法調用

[Test] 
    public void MarkAsSuccessfulTest() 
    { 
     //setup data 
     var payment = Util.DbUtil.CreateNewRecurringProfilePayment(); 

     //unit test 

     var mockNotificationSender = new Mock<IMarkAsSuccessfulNotificationSender>(); 
     var mockCommandHandler = new Mock<IDbCommandHandler<RecurringPaymentMarkAsSuccessfulCommand>>(); 

     var classUnderTest = new RecurringProfileMarkLastPaymentAsSuccessful(mockCommandHandler.Object, mockNotificationSender.Object); 

     classUnderTest.MarkAsSuccessful(payment.RecurringProfile); 
     mockCommandHandler.Verify(x=>x.Handle(It.IsAny<RecurringPaymentMarkAsSuccessfulCommand>()), Times.Once()); 
     mockNotificationSender.Verify(x=>x.SendNotification(payment), Times.Once()); 

    } 

的問題是與線:

mockCommandHandler.Verify(x=>x.Handle(It.IsAny<RecurringPaymentMarkAsSuccessfulCommand>()), Times.Once()) 

這驗證.Handle()方法是調用。但是,這對於測試是不夠的 - 這個.Handle()接受一個命令參數,它有一個屬性 - Payment。我想驗證此參數實際上是否與payment變量匹配。

這是可能的,還是有一些代碼設計的問題?

回答

3

您可以爲參數驗證提供斷言:

mockCommandHandler.Verify(x => 
    x.Handle(It.Is<RecurringPaymentMarkAsSuccessfulCommand>(c => c.Payment == payment)) 
    , Times.Once()); 
+0

哇這很快:)完美的作品,謝謝! –

0

您正在使用It.IsAny()。您可以使用It.Is()......像下面這樣:

mockCommandHandler.Verify(x => x.Handle(It.Is<RecurringPaymentMarkAsSuccessfulCommand>(command => command.Payment == payment)), Times.Once()); 

您可以使用It.Is()來檢查在傳遞的參數一定的條件下如果它是字面上相同的參考,你可以按照你與你的第二檢驗做什麼,而不是你的代碼更改爲以下:

mockCommandHandler.Verify(x => x.Handle(payment), Times.Once()); 
+0

這是一個完全有效的答案,它似乎是一個答案几乎在同一時間發佈 - 不幸的是不能標記爲全部答案,因此必須標記此處顯示的第一個答案!謝謝:) –

相關問題