我有以下测试用例:
[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
变量匹配。
这是可能的,还是某些代码设计存在问题?
答案 0 :(得分:3)
您可以为参数验证提供谓词:
mockCommandHandler.Verify(x =>
x.Handle(It.Is<RecurringPaymentMarkAsSuccessfulCommand>(c => c.Payment == payment))
, Times.Once());
答案 1 :(得分: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());