我正在创建一个部分模拟来测试基类的受保护助手方法。我对关于受保护方法是否应该存在或者是否应该是注入依赖的辩论不太感兴趣,因为我真的很想看到下面的过程工作。
EnumerationServiceBase_Accessor是VSTS 2010生成的私有访问对象。下面的所有内容都运行良好,除了第17行没有有效地设置一个期望来拦截对CreateNewContextResponse(request)的调用这一事实,这是在播放期间被partialTarget.EnumerateOp(request)调用的受保护方法。而是调用基类的实际实现。我在这里做错了什么?
1 PrivateObject p = new PrivateObject(mocks.PartialMock<EnumerationServiceBase>(contextManager, requestValidator, configProvider, faultProvider, logger));
2 EnumerationServiceBase_Accessor partialTarget = mocks.PartialMock<EnumerationServiceBase_Accessor>(p);
3
4 EnumerateOpRequest request = new EnumerateOpRequest()
5 {
6 Enumerate = new Enumerate()
7 {
8 Item = new EnumerateNewContext()
9 }
10 };
11
12 using (mocks.Record())
13 {
14 requestValidator.Expect(r => r.ValidateEndTo(request));
15 requestValidator.Expect(r => r.ValidateMaxElements(request, allowNulls: true));
16 partialTarget.Expect(t => t.EnumerateOp(request)).CallOriginalMethod(OriginalCallOptions.CreateExpectation);
17 partialTarget.Expect(t => t.CreateNewContextResponse(request)).Return(null);
18 contextManager.Expect(t => t.RemoveExpiredContexts());
19 }
20
21 using (mocks.Playback())
22 {
23 partialTarget.EnumerateOp(request);
24 }
这是EnumerateOp(请求),在EnumerationServiceBase.cs中实现
1 public virtual EnumerateOpResponse EnumerateOp(EnumerateOpRequest request)
2 {
3 EnumerateOpResponse response = null;
4
5 if (request.Enumerate.Item is EnumerateNewContext)
6 {
7 try
8 {
9 _contextManager.RemoveExpiredContexts();
10 }
11 catch (Exception ex)
12 {
13 _logger.Warn("We're not cleaning up contexts effectively.", ex);
14 }
15
16 _requestValidator.ValidateEndTo(request);
17 _requestValidator.ValidateMaxElements(request, allowNulls: true);
18 response = CreateNewContextResponse(request);
19 }
20 else if (request.Enumerate.Item is EnumerationContextType)
21 {
22 _requestValidator.ValidateMaxElements(request, allowNulls: false);
23 response = CreateEnumerationContextResponse(request);
24 }
25 else
26 {
27 throw _faultProvider.GetItemNotRecognizedFault("The Enumerate.Item value was not of type EnumerateNewContext or EnumerationContextType.");
28 }
29 return response;
30 }
编辑:删除了不必要的信息。
答案 0 :(得分:2)
问题是您的CreateNewContextResponse
受到保护且You can't mock protected methods with Rhino Mocks.