Update:
Complete code example:
public class DelegatingHandlerStub : DelegatingHandler {
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handlerFunc;
public DelegatingHandlerStub() {
_handlerFunc = (request, cancellationToken) => Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
}
public DelegatingHandlerStub(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handlerFunc) {
_handlerFunc = handlerFunc;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
return _handlerFunc(request, cancellationToken);
}
}
public async Task Should_Return_Ok() {
//Arrange
var expected = "Hello World";
var mockFactory = new Mock<IHttpClientFactory>();
var configuration = new HttpConfiguration();
var clientHandlerStub = new DelegatingHandlerStub((request, cancellationToken) => {
request.SetConfiguration(configuration);
var response = request.CreateResponse(HttpStatusCode.OK, expected);
return Task.FromResult(response);
});
var client = new HttpClient(clientHandlerStub);
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);
IHttpClientFactory factory = mockFactory.Object;
var controller = new ValuesController(factory);
//Act
var result = await controller.Get();
//Assert
result.Should().NotBeNull();
var okResult = result as OkObjectResult;
var actual = (string) okResult.Value;
actual.Should().Be(expected);
}
Original:
I'm following this guide to mock IHttpClientFactory
.
https://stackoverflow.com/a/54227679/3850405
For it to work I need the following line:
var configuration = new HttpConfiguration();
Visual Studios fix is Install package 'Microsoft.AspNet.WebApi.Core'
.
This works and the code runs fine but I get the following warning:
Warning NU1701 Package 'Microsoft.AspNet.WebApi.Core 5.2.7' 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' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project.
I have tried to install Microsoft.AspNetCore.Mvc.WebApiCompatShim
that was recommended below but it does not work.
https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.WebApiCompatShim
https://stackoverflow.com/a/57279121/3850405
Is there another NuGet that can be used to solve this?
Looking at dependencies for Microsoft.AspNet.WebApi.Core
it is only dependent on Microsoft.AspNet.WebApi.Client
that in turn uses .NETStandard 2.0
. Ideally I would not like to create a new project targeting .NET Standard 2.0
and put the code in there. I would like to use the .NET 5
project.
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Core/
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/
https://learn.microsoft.com/en-us/dotnet/standard/net-standard