Here is info about our technical development environment :
• .NET 6
• C# 10
• Visual Studio 2022
I’m trying to Mock System.Net.Http.HttpMessageHandler in my mock Unit test code.
Mock<HttpMessageHandler> handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
.Protected()
// Setup the PROTECTED method to mock
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
// prepare the expected response of the mocked http call
.Returns(async (HttpRequestMessage request, CancellationToken token) =>
{
HttpResponseMessage response = new HttpResponseMessage();
response.Headers.Add("Date", "Mon, 17 Apr 2023 14:55:43 GMT");
response.Headers.Add("Server", "Warp/3.3.23");
response.Headers.Add("X-Request-ID", "adaf6342-a007-4155-8480-4cd2eacc3a0b");
response.Content = ….fill-in-blank code…….
response.StatusCode = HttpStatusCode.OK;
//...decide what to put in the response after looking at the contents of the request
return response;
}).Verifiable();
To get more specific, Microsoft.Net.Http.Client package contains the HttpConnectionResponseContent class ( which inherits from HttpContent ).
In the fill-in-blank code area above, I’m trying to implement something like the following code excerpt:
response.Content = System.Net.Http.HttpConnectionResponseContent(….)
I’ve been searching the internet to find what dll package contains System.Net.Http.HttpConnectionResponseContent API. However, it’s a little strange, I found the following github.com link:
It indicates that the HttpConnectionResponseContent class is part of the Microsoft.Net.Http.Client namespace
However, when I added Microsoft.Net.Http.Client package dll reference to my .NET 6-based solution, it gives the following warning:
Package 'Microsoft.Net.Http 2.2.29' was restored using '.NETFramework,Version=v4.6.1,
.NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1,
.NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1'
instead of the project target framework 'net6.0'. This package may not be fully compatible
with your project.
Furthermore, it shows the problem because when I added the namespace, it states that the following namespace does not exist:
using Microsoft.Net.Http;
Could someone please post back code and explain how I can implement something along the following sample code?
response.Content = System.Net.Http.HttpConnectionResponseContent(….)