【问题标题】:How to mock(rhino.mocks) response object from base.SendAsync() in MVC4.5 Web API handler SendAsync() method如何在 MVC4.5 Web API 处理程序 SendAsync() 方法中从 base.SendAsync() 模拟(rhino.mocks)响应对象
【发布时间】:2013-03-22 11:12:35
【问题描述】:

我必须使用 Rhino.Mock 在 ASP.NET MVC Web API 控制器上编写单元测试 我有一个名为 AHandler.cs 的处理程序,它来自 System.Net.Http.HttpClientHandler 类。 AHandler.cs的singnature SendAsync方法如下:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
.....
 var response = base.SendAsync(request, cancellationToken).Result; 
 if (response.IsSuccessStatusCode)
 {
   .....
 }
}

上面的 base 关键字表示 HttpClientHandler 并且它的 SendAsync() 方法是“受保护的”!!! 现在我尝试模拟对象“base.SendAsync(request,cancellationToken).Result”并得到我想要的手工响应结果。 但是当我编写以下代码时,似乎Rhino mocks看不到“base”关键字:

var mockbase = MockRepository.GenerateMock<AHandler>;
mockbase.Stub(x => x.base <=== can't see base keyword
                 ^^^^^

所以我换一种方式,尝试模拟 HttpClientHandler 类

var mockbase = MockRepository.GenerateMockHttpClientHandler>;
mockbase.Stub(x => x.  <== I can't see SendAsync() method, becase it is protected !!

现在我真的很痛苦!! 谁能给我一些建议,告诉我如何在 MVC 处理程序中做出自定义响应?! 非常感谢!!

【问题讨论】:

    标签: c# unit-testing asp.net-web-api rhino-mocks


    【解决方案1】:

    为什么要首先模拟处理程序?您可以为您的测试注入一个特定的虚拟实现。该处理程序将返回您的测试所期望的新 HttpResponse 消息。

    public class MyDummyHttpHandler : DelegatingHandler
    {
      HttpResponseMessage response;
    
      public MyDummyHttpHandler(HttpResponseMessage response)
      {
        this.response = response;
      }
    
      protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,    CancellationToken cancellationToken)
      {
        .....
        TaskCompletionSource<HttpResponseMessage> tsc = new TaskCompletionSource<HttpResponseMessage>();
        tsc.SetResult(this.response);
    
        return tsc.Task;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多