Skip to content
Pure Krome edited this page Apr 26, 2017 · 2 revisions

The Basics

There's two main classes that you need to care about, when faking your HttpClient stuff in your unit tests:

  • FakeHttpMessageHandler
  • HttpMessageOptions

FakeHttpMessageHandler

This is some magical unit-test friendly wrapper class which HttpClient uses under it's hood. We can't mock out the HttpClient class ... instead of fake out some secret implementation magic that occurs inside of HttpClient.

So that's what this class does -> when HttpClient tries to go off to some Uri/endpoint, this class takes over and does whatever you've asked it to do ... which you define in the HttpMessageOptions ...

HttpMessageOptions

This is the main customizable section which the HttpClient will end up using.

  • RequestUri : Required: End Uri we are targetting (e.g. https://api.YouWebsite.com/something/here). If not supplied, it will default to null which means "any Uri / we don't care what Uri you are going to hit".
  • HttpResponseMessage : Required: Need to know what type of response we will return. (i.e. Status code, content, response headers, etc).
  • HttpMethod : Optional: If not provided, then assumed to be any method. (i.e. HTTP GET, HTTP POST, etc)
  • HttpContent : Optional: If not provided, then assumed to be no content.
  • Headers : Optional: If not provided, then assumed to have no headers.

And finally ... one of the most important features of this class is ...

  • NumberOfTimesCalled : How many times this HttpMessageOptions instance was 'used' by the HttpClient instance when it was doing some network calls.

How do I use all of these parts?

  1. (Arrange) You setup up your HttpMessageOptions
  2. (Arrange) Create an FakeHttpMessageHandler instance with your options.
  3. (Arrange) Create an HttpClient instance with your fake message handler.
  4. (Act) Call an endpoint using your HttpClient instance.
  5. (Assert) Assert your NumberOfTimesCalled on your options instance to prove that your HttpClient exactly called the expected endpoint.