2013-12-20 36 views
2

如何使用RhinoMocks模擬以下行爲?如何在RhinoMocks中通過指定的條件返回方法的值?

被測試的方法在接口上調用ReceivePayment方法。

public void TestedMethod(){ 
    bool result = interface.ReceivePayment();   
} 

接口有CashAccepted事件。 如果此事件已被多次調用(或通過條件),ReceivePayment shoud將返回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; 
    } 

StartCashReceiving立即返回。 但是下一行:paymentSysProvider.Raise(...)正在等待ReceivePayment存根的完成!

回答

2

您可以使用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. 
2

您是否在測試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-do http://weblogs.asp.net/psteele/archive/2011/02/02/using-lambdas-for-return-values-in-rhino-mocks.aspx

+0

非常感謝。恩......好吧,我試圖測試這個類的複雜行爲。如果指定的條件得到滿足,ReceivePayment必須返回true。爲了滿足條件,我必須提高CashAccepted事件。 – EngineerSpock

相關問題