As part of an ASP.Net Core project that I am working on I have a requirement to communicate with a number of different Rest based API Endpoints from within my WebApi. To achieve this I am using a number of service classes that each instantiate a static HttpClient
. Essentially I have a service class for each of the Rest based endpoints that the WebApi connects to.
An example of how the static HttpClient
is instantiated in each of the service classes can be seen below.
private static HttpClient _client = new HttpClient()
{
BaseAddress = new Uri("http://endpointurlexample"),
};
Whilst the above is working well, it does not allow for effective unit testing of the service classes that are using HttpClient
. To enable me to carry out unit testing I have a fake HttpMessageHandler
that I would like to use for the HttpClient
in my unit tests, whilst the HttpClient
is instantiated as above however I am unable to apply the fake HttpMessageHandler
as part of my unit tests.
What is the best way for the HttpClient
in the service classes to remain a single instance throughout the application (one instance per endpoint), but to allow a different HttpMessageHandler
to be applied during the unit tests?
One approach I have thought of would be not to use a static field to hold the HttpClient
in the service classes, rather to allow it to be injected via constructor injection using a singleton lifecycle, which would allow me to specify a HttpClient
with the desired HttpMessageHandler
during unit tests, the other option I thought of would be to use a HttpClient
Factory Class that instantiated the HttpClient
s in static fields that could then be retrieved by injecting the HttpClient
factory into the service classes, again allowing a different implementation with the relevant HttpMessageHandler
to be returned in unit tests. None of the above feel particularly clean however and it feels like there must be a better way?
Any questions, let me know.