2012-06-01 56 views
2

我嘗試了RhinoMocks(只是剛剛開始,請溫柔!),並很困惑,當輸入欄爲什麼如果我用這個設置:RhinoMocks - 無法投Foo類型使用非靜態庫

var mockRepos = new MockRepository(); 
var mockServiceProvider = mockRepos.DynamicMock<IServiceProvider>(null); 
var mockContext = mockRepos.DynamicMock<IPluginExecutionContext>(null); 

mockServiceProvider.Expect(x => x.GetService(typeof(IPluginExecutionContext))).Return(mockContext); 

var someSampleClass = new SomeClassOrOther(mockServiceProvider); 

在SomeClassOrOther某一點,該方法GetService被稱爲

var context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); 

,並導致異常:

Unable to cast object of type 'Castle.Proxies.ObjectProxyd0bf4b879a6341bbba3478cf1189d621' to type 'Microsoft.Xrm.Sdk.IPluginExecutionContext'. 

但是,如果我使用:

var mockServiceProvider = MockRepository.GenerateMock<IServiceProvider>(null); 
var mockContext = MockRepository.GenerateMock<IPluginExecutionContext>(null); 

mockServiceProvider.Expect(x => x.GetService(typeof(IPluginExecutionContext))).Return(mockContext); 

即靜態MockRepository.GenerateMock並沒有錯誤執行。

我在哪裏錯了?

+0

啊,我用期待。我應該使用存根嗎? – glosrob

+0

如果您稍後未驗證期望,請使用存根。 –

回答

2

我不知道你爲什麼會得到這個例外。但是,當使用「舊」非靜態語法時,您會在「記錄」狀態中進行嘲弄。使用它們之前,你需要把它們設置在回放模式:

var mockRepos = new MockRepository(); 
var mockServiceProvider = mockRepos.DynamicMock<IServiceProvider>(); 
var mockContext = mockRepos.DynamicMock<IPluginExecutionContext>(); 

mockRepos.ReplayAll(); 

mockServiceProvider 
    .Stub(x => x.GetService(typeof(IPluginExecutionContext))) 
    .Return(mockContext); 

var someSampleClass = new SomeClassOrOther(mockServiceProvider); 
+0

就是這個,謝謝。 – glosrob

1

你是混合新AAA語法和老Record/Replay語法。當您使用Expect擴展方法和新的AAA語法時,您不需要在mocks存儲庫上進行操作並手動更改其模式(記錄/重放)。創建新的靜態方法模擬考試(其中創建重播模式嘲笑),後來覈實的期望:

// Arrange 
var mockServiceProvider = MockRepository.GenerateMock<IServiceProvider>(); 
var mockContext = MockRepository.GenerateMock<IPluginExecutionContext>(); 

mockServiceProvider.Expect(x => x.GetService(typeof(IPluginExecutionContext))) 
        .Return(mockContext); 

var someSampleClass = new SomeClassOrOther(mockServiceProvider); 
// Act 

// Assert 
mockServiceProvider.VerifyAllExpectations(); 

這裏是老Record/Replay語法比較:

var mockRepos = new MockRepository(); 
var mockServiceProvider = mockRepos.DynamicMock<IServiceProvider>(); 
var mockContext = mockRepos.DynamicMock<IPluginExecutionContext>(); 

Expect.Call(mockServiceProvider.GetService(typeof(IPluginExecutionContext))) 
     .Return(mockContext); 
mockRepos.ReplayAll(); 

var someSampleClass = new SomeClassOrOther(mockServiceProvider); 
// exercise your SUT 
mockRepos.VerifyAll(); 
相關問題