我正在创建一个部分模拟来测试基类的受保护辅助方法。我对是否应该存在受保护的方法或者它是否应该是注入依赖项的辩论不太感兴趣,因为我真的很想看到下面的过程工作。
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 }
这是 EnumerationServiceBase.cs 中实现的 EnumerateOp(request)
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 }
编辑:删除了不必要的信息。