2011-10-11 90 views
6

如何在RhinoMocks中執行一個存根對象來爲其上的void方法返回void?我該如何強制一個void方法從Stub對象返回Void?

拿這個例子:

public interface ICar 
{ 
    string Model {get;set;} 
    void Horn(); 
} 

ICar stubCar= MockRepository.GenerateStub<ICar>(); 
stubCar.Expect(c=>c.Horn()).Return(//now what so that 
            // it returns nothing as the meth. returns void ? 
+0

如果使用void返回類型定義它,_could_它將如何返回任何內容? – CodingGorilla

+0

我的擔心是如果我不強制它返回void,對這個存根的調用會拋出一個異常。我試過並看到:喬恩是對的! – pencilCake

回答

8

方法不能返回值 - 這是一個無效的方法。 CLR不會它嘗試返回一個值。你不需要爲此測試。

您只需撥打Expect

6

Return()方法對於void方法調用無效。相反,你想是這樣的:

ICar stubCar= MockRepository.GenerateStrictMock<ICar>(); 
stubCar.Expect(c=>c.Horn()); 
stubCar.DoSomethingThatIsSupposedToCallHorn(); 
stubCar.VerifyAllExpectations(); 

它會告訴你是否Horn()被調用。

這就是測試單元測試時調用void方法的方法。你做到以下幾點:

  1. 設置的期望(Expect()
  2. 調用方法應該調用預期
  3. 驗證預期的方法被調用。
+0

我不認爲這將工作,因爲您使用的是存根並非模擬,存根將始終通過VerifyAllExpectations 請參閱:http://www.wrightfully.com/on-rhino-mocks-verifyallexpectations-vs-assertwascalled/ – crabCRUSHERclamCOLLECTOR

+0

這應該是一個嚴格的模擬。我會改變它。感謝您的支持。 –