Stage | CI | NuGet |
---|---|---|
Production | ||
Development |
Code that uses System.Net.Http.HttpClient
will attempt to actually call/hit that Http endpoint.
To prevent this from happening in a unit test, some simple helpers are provided in this code library.
- ✅ Hijack your
httpClient
request to return some hardcoded response (this library makes it supa dupa easy to do this) - ✅ Works with GET/POST/PUT/etc.
- ✅ Can provide wildcards (i.e. I don't care about the Request endpoint or the request HTTP Method, etc)
- ✅ Can provide multiple endpoints and see handle what is returned based on the particular request.
- ✅ Can confirm the number of times an endpoint was attempted to be hit.
- ✅ Can be used to test network errors during transmission. i.e. can test when the HttpClient throws an exception because of .. well ... 💥
Package Name: WorldDomination.HttpClient.Helpers
CLI: install-package WorldDomination.HttpClient.Helpers
What is HttpClientFactory
? Read up about it here. You should be using that in your applications, peeps.
// Service that accepts an HttpClient so it has been setup to work nicely with HttpClientFactory.
public class MyService : IMyService
{
public MyService(HttpClient httpClient)
{ .. }
public async Task<string> GetWebApiStuffAsync() { .. }
}
// ** Now for a sample test **
// Act.
// Setup which http request 'stuff' you wish to capture and return.
// E.g. If we hit "this url" then return "this payload" and "this response type. 200 OK, etc".
var options = new HttpMessageOptions { ....};
// Create the fake handler with the specific options to check for.
var messageHandler = new FakeHttpMessageHandler(options);
// Now create a simple HttpClient which will use the fake handler to
// cut short / capture the request.
var httpClient = new HttpClient(messageHandler);
var service = new MyService(httpClient);
// Act.
await service.GetWebApiStuffAsync();
There's plenty more examples about to wire up:
- A really simple example
- Multiple endpoints at once
- Wildcard endpoints
- Throwing exceptions and handling it
For all the samples, please check out the Wiki page: Helper Examples
Special Ackowledgements
A special and sincere thank you to David Fowler (@davidfowl) who explained how I should be unit testing the HttpClient
class and gave me the guidence to make this library. I was soooo on the wrong path - and he guided me back on track.
Thank you David! 👌 🍸 👾
Finally, unit testing HttpClient
is now awesome and simple!