2

我正在尝试 RhinoMocks(才刚刚开始,请温柔一点!)并且很困惑为什么我使用这个设置:

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,它执行没有错误。

我在哪里错了?

4

2 回答 2

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);
于 2012-06-01T12:21:58.843 回答
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();  
于 2012-06-01T13:29:03.330 回答