john smith
john smith

Reputation: 157

How can you shim/fake HttpClient.GetAsync

I have a processor that handles calling to an endpoint and returning the response. The method is shown below

public Event GetEvent()
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("https://www.test.com");

    HttpResponseMessage response = client.GetAsync("/event").GetAwaiter().GetResult();

    var content = response.Content.ReadAsStringAsync().Result;
    Event newEvent = JsonConvert.DeserializeObject<Event>(content);

    response.EnsureSuccessStatusCode();

    return newEvent;
}

Now I need to create a unit test for this class that does not actually make the request to the endpoint. My unit test follows this pattern:

 public HttpClientProcessorTest()
 {
     InstantiateClassUnderTest();
 }

  [Fact]
  public void HttpClientProcessor_GetEvent_EnsuresSuccessfulStatusCodeAndReturnsEvent()
  {
      ShimHttpClient.AllInstances.GetAsync = (x) =>
      {

      };

      ClassUnderTest.GetEvent();
  }

However I get the error 'ShimHttpClient.AllInstances' does not contain a definition for 'GetAsync'. I added System.Net.Http to the references, right-clicked and added fakes assembly, but it is only providing access to some of the methods, not GetAsync(). I left out the asserts because they are not needed until I can even get the shim working.

How can I shim GetAsync()?

Upvotes: 0

Views: 1444

Answers (1)

Sergii Lebid
Sergii Lebid

Reputation: 63

I implemented it in this way :

Code:

       HttpClientHandler handler = new HttpClientHandler();
       HttpClient httpClient = new HttpClient(handler);

       Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
       HttpResponseMessage httpResponse = httpRequest.Result;

In the test:

       ShimHttpClient.AllInstances.SendAsyncHttpRequestMessageHttpCompletionOptionCancellationToken = (r,a, message, s) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));

Upvotes: 1

Related Questions