Stubbing or Mocking ASP.NET Web API HttpClient

前端 未结 3 2010
天命终不由人
天命终不由人 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:42

    I released a library a few months ago called MockHttp which might be useful. It uses a custom HttpMessageHandler with a fluent (and extensible) API. You can inject the mocked handler (or HttpClient) into your service class and it will respond as it was configured.

    Below shows basic usage. The When and Respond methods have a bunch of overloads, including running custom logic. The documentation on the GitHub page goes into a lot more detail.

    var mockHttp = new MockHttpMessageHandler();
    
    // Setup a respond for the user api (including a wildcard in the URL)
    mockHttp.When("http://localhost/api/user/*")
            .Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON
    
    // Inject the handler or client into your application code
    var client = new HttpClient(mockHttp);
    
    var response = async client.GetAsync("http://localhost/api/user/1234");
    // or without async: var response = client.GetAsync(...).Result;
    
    var json = await response.Content.ReadAsStringAsync();
    
    // No network connection required
    Console.Write(json); // {'name' : 'Test McGee'}
    

提交回复
热议问题