

If we had multiple test projects, each one would need a copy of that interface or a reference to a common project.
#Http client factory code
This is starting to turn into a lot of code already, though, and to make matters worse we’ve had to create an interface. Under the hood, Moq uses reflection to retrieve the target method on the real class and then rewrites the expression to call the otherwise-inaccessible method. In order to target this method in a setup the usual way, though - with a lambda and IntelliSense as opposed to passing its name as a string - we need to create a dummy interface that contains the same method, which we use like so: var handler = new Mock () var client = new HttpClient ( handler, false ) handler.

Luckily, Moq provides a way of mocking protected methods, and since it’s abstract, the mock can implement it.

Unfortunately, not only does HttpMessageHandler not implement an interface, but the SendAsync method is protected: protected internal abstract Task SendAsync ( HttpRequestMessage request, CancellationToken cancellationToken ) Rather than mock HttpClient itself (whose methods are not virtual anyway), we would mock its handler.

Incidentally, this is a rather powerful yet little-known feature of HttpClient, as it allows for creating a DelegatingHandler that acts as middleware around the request pipeline ( this page explains, albeit in the context of classic ASP.NET). HttpClient itself is merely a set of helpers wrapping an HttpMessageHandler all requests ultimately go through the handler’s sole SendAsync method. With the help of extension methods, mocking HTTP requests can be just as easy as mocking a service method. The one we’ll use for this example is: services.AddHttpClient () Behind the scenes this will register a few required services, one of which will be an implementation of IHttpClientFactory. Here I’ll show how we can use Moq with HttpClient as well. The HttpClientFactory includes various ServiceCollection extensions. Required instances can be enabled and disabled as required. The solution has generally been to either create a wrapper of some form to mock instead (at the cost of cluttering the code) or use an HttpClient-specific testing library (which requires switching to a separate mocking system for HTTP calls and may not fit well alongside other mocks). HTTPClientFactory lets you DI inject the HTTPClient objects using an explicit dependency principle. NSwag.Mocking HttpClient directly is notoriously difficult.Allows to run the NSwag command line tool in an MSBuild target (.Use HTTP Client Factory with NSwag Generated Classes :.
#Http client factory download
