如何使用RhinoMocks模拟以下行为?
测试的方法在接口上调用接收付款方法。
public void TestedMethod(){
bool result = interface.ReceivePayment();
}
接口具有 CashAccepted 事件。如果此事件已多次调用(或按条件调用),则接收付款应返回 true。
如何完成这样的任务?
更新。
现在我执行以下操作:
UpayError error;
paymentSysProvider.Stub(i => i.ReceivePayment(ticketPrice,
App.Config.SellingMode.MaxOverpayment, uint.MaxValue, out error))
.Do( new ReceivePaymentDel(ReceivePayment));
paymentSysProvider.Stub(x => x.GetPayedSum()).Return(ticketPrice);
session.StartCashReceiving(ticketPrice);
paymentSysProvider.Raise(x => x.CashInEvent += null, cashInEventArgs);
public delegate bool ReceivePaymentDel(uint quantityToReceive, uint maxChange, uint maxTimeout, out UpayError error);
public bool ReceivePayment(uint quantityToReceive, uint maxChange, uint maxTimeout, out UpayError error) {
Thread.Sleep(5000);
error = null;
return true;
}
开始现金立即接收回报,因为里面有一个任务启动。但是下一行:paymentSysProvider.Raise(...) 正在等待 ReceivePayment 存根的完成!
WhenCalled
.其实我不明白你的问题(事件是由模拟还是由被测单位触发的?谁在处理事件?
有一些示例代码:
bool fired = false;
// set a boolean when the event is fired.
eventHandler.Stub(x => x.Invoke(args)).WhenCalled(call => fired = true);
// dynamically return whether the eventhad been fired before.
mock
.Stub(x => x.ReceivePayment())
.WhenCalled(call => call.ReturnValue = fired)
// make rhino validation happy, the value is overwritten by WhenCalled
.Return(false);
当您在测试中触发事件时,您还可以在触发后重新配置模拟:
mock
.Stub(x => x.ReceivePayment())
.Return(false);
paymentSysProvider.Raise(x => x.CashInEvent += null, cashInEventArgs);
mock
.Stub(x => x.ReceivePayment())
.Return(true)
.Repeat.Any(); // override previous return value.
你在测试ReceivePayment吗?如果没有,您真的不应该担心该接口是如何实现的(请参阅 http://blinkingcaret.wordpress.com/2012/11/20/interaction-testing-fakes-mocks-and-stubs/)。
如果必须,可以使用 .做扩展方法,例如:
interface.Stub(i => i.ReceivePayment()).Do((Func<bool>) (() => if ... return true/false;));
看:http://ayende.com/blog/3397/rhino-mocks-3-5-a-feature-to-be-proud-of-seamless-dohttp://weblogs.asp.net/psteele/archive/2011/02/02/using-lambdas-for-return-values-in-rhino-mocks.aspx