Stubbing or Mocking ASP.NET Web API HttpClient

前端 未结 3 2008
天命终不由人
天命终不由人 2020-12-25 13:02

I am using the new Web API bits in a project, and I have found that I cannot use the normal HttpMessageRequest, as I need to add client certificates to the requ

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-25 13:41

    I use Moq and I can stub out the HttpClient. I think this the same for Rhino Mock (I haven’t tried by myself). If you just want to stub the HttpClient the below code should work:

    var stubHttpClient = new Mock();
    ValuesController controller = new ValuesController(stubHttpClient.Object);
    

    Please correct me if I’m wrong. I guess you are referring to here is that stubbing out members within HttpClient.

    Most popular isolation/mock object frameworks won’t allow you to stub/setup on non- virtual members For example the below code throws an exception

    stubHttpClient.Setup(x => x.BaseAddress).Returns(new Uri("some_uri");
    

    You also mentioned that you would like to avoid creating a wrapper because you would wrap lot of HttpClient members. Not clear why you need to wrap lots of methods but you can easily wrap only the methods you need.

    For example :

    public interface IHttpClientWrapper  {   Uri BaseAddress { get;  }     }
    
    public class HttpClientWrapper : IHttpClientWrapper
    {
       readonly HttpClient client;
    
       public HttpClientWrapper()   {
           client = new HttpClient();
       }
    
       public Uri BaseAddress   {
           get
           {
               return client.BaseAddress;
           }
       }
    }
    

    The other options that I think might benefit for you (plenty of examples out there so I won’t write the code) Microsoft Moles Framework http://research.microsoft.com/en-us/projects/moles/ Microsoft Fakes: (if you are using VS2012 Ultimate) http://msdn.microsoft.com/en-us/library/hh549175.aspx

提交回复
热议问题