2011-08-09 70 views
20

使用RhinoMocks,我試圖存根屬性的getter值。該屬性被定義爲只有getter訪問權的接口的一部分。打樁一個屬性得到使用犀牛製品

但是,我得到錯誤「無效的調用,最後一次調用已被使用或沒有調用(確保您正在調用虛擬(C#)/ Overridable(VB)方法)」。我理解這可能意味着我所存的財產不是虛擬的;然而,它是接口的一部分,我不知道這是爲什麼我得到這個錯誤的原因..

下面是代碼框架。如果我取消它說行「stubRepository.Stub(X => x.StoreDeviceID).PropertyBehavior();」,然後我得到一個新的錯誤「屬性必須讀/寫」。我搜索了SO,發現this頁面。但建議的解決方案並不能幫助我。有什麼想法嗎?

public interface IStore { 
     string StoreDeviceID {get;} 
     //other methods 
    } 

    public static class Store { 
     private IStore Repository; 

     public void SetRepository(IStore rep){ 
      Repository = rep; 
     } 

     public StoredeviceID { 
      get{ 
       return Repository.StoreDeviceID; 
      } 
     } 

     //other methods 
    } 

    public class TestClass { 
     [Test] 
     public void TestDeviceID() { 
      var stubRepository = 
       MockRepository.GenerateStub<IStore>(); 
      Store.SetRepository(stubRepository); 

      //stubRepository.Stub(x => x.StoreDeviceID).PropertyBehavior(); 
      SetupResult.For(stubRepository.StoreDeviceID).Return("test"); 

      Assert.AreSame(Store.StoreDeviceID, "test"); 
     } 
    } 

回答

28

由於這是一個只讀屬性,你需要說:

stubRepository.Stub(x => x.StoreDeviceID).Return("test"); 
與存根

通常情況下,屬性用於像正常的C#特性。因此,對於非只讀屬性,你會說:stubRepository.someProperty = "test";

另外請注意,如果你想建立一個方法表現一定的方式,無論它是一個模擬或短線,你總是說:

stubRepository.Stub(x => x.someMethod()).Return("foo"); 

記住,存根都沒有與他們所需的依賴提供您的單元測試,但不上運行驗證;這就是嘲笑的目的。

當你要提供一個行爲以某種方式依賴使用存根。當您想驗證某個依賴項已正確交互時使用模擬。

從(優秀)Rhino Wiki

A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred. A stub is an object that you use in order to pass to the code under test. You can setup expectations on it, so it would act in certain ways, but those expectations will never be verified. A stub's properties will automatically behave like normal properties, and you can't set expectations on them.

If you want to verify the behavior of the code under test, you will use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn't the focus of this test, you will use a stub.

IMPORTANT: A stub will never cause a test to fail.

+0

@亞當,因爲屬性是隻讀的,我無法設置就可以了。但是,您提供給Stub屬性的代碼片段完美無缺。我傻,我想除了:) – Santhosh

+0

StoreDeviceID所有其他選項沒有一個二傳手,讓您的第一條語句'stubRepository.StoreDeviceID =「測試」;'將無法工作。 –

+0

啊 - 對不起。我會更新我的答案 - 很高興你能夠正常工作。 –

4

你可以做一個存根如下:

stubRepository.Stub(x => x.StoreDeviceID).Return("test"); 

這將導致它返回 「測試」,以StoreDeviceID的獲取任何電話。