-
-
Notifications
You must be signed in to change notification settings - Fork 11
The Basics
Pure Krome edited this page Apr 26, 2017
·
2 revisions
There's two main classes that you need to care about, when faking your HttpClient
stuff in your unit tests:
FakeHttpMessageHandler
HttpMessageOptions
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
...
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 tonull
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 thisHttpMessageOptions
instance was 'used' by theHttpClient
instance when it was doing some network calls.
- (Arrange) You setup up your
HttpMessageOptions
- (Arrange) Create an
FakeHttpMessageHandler
instance with your options. - (Arrange) Create an
HttpClient
instance with your fake message handler. - (Act) Call an endpoint using your
HttpClient
instance. - (Assert) Assert your
NumberOfTimesCalled
on your options instance to prove that yourHttpClient
exactly called the expected endpoint.
- The Basics
- Common 'Happy Path' usages
- Common 'Sad Panda' usages
- Other interesting stuff