更新:
完整的代码示例:
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);
}
原来的:
我正在按照本指南进行模拟IHttpClientFactory
。
https://stackoverflow.com/a/54227679/3850405
为了使它工作,我需要以下行:
var configuration = new HttpConfiguration();
Visual Studios 修复是Install package 'Microsoft.AspNet.WebApi.Core'
.
这有效,代码运行良好,但我收到以下警告:
警告 NU1701 包 'Microsoft.AspNet.WebApi.Core 5.2.7' 已使用 '.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' 而不是项目目标框架'net5.0'。此软件包可能与您的项目不完全兼容。
我尝试安装Microsoft.AspNetCore.Mvc.WebApiCompatShim
下面推荐的,但它不起作用。
https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.WebApiCompatShim
https://stackoverflow.com/a/57279121/3850405
是否有另一个 NuGet 可以用来解决这个问题?
查看依赖关系Microsoft.AspNet.WebApi.Core
只依赖于Microsoft.AspNet.WebApi.Client
它反过来使用.NETStandard 2.0
. 理想情况下,我不想创建一个新的项目目标.NET Standard 2.0
并将代码放在那里。我想使用该.NET 5
项目。
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Core/
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/
https://docs.microsoft.com/en-us/dotnet/standard/net-standard