.NET 5 项目中 System.Web.Http 的 HttpConfiguration

HttpConfiguration from System.Web.Http in .NET 5 project

更新:

完整代码示例:

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

为了让它工作,我需要以下行:

var configuration = new HttpConfiguration();

Visual Studios 修复是 Install package 'Microsoft.AspNet.WebApi.Core'

这有效,代码运行良好,但我收到以下警告:

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.

我已尝试安装下面推荐的 Microsoft.AspNetCore.Mvc.WebApiCompatShim,但它不起作用。

https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.WebApiCompatShim

是否有另一个 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

如果这是出于测试目的,我建议使用存根而不是模拟。 CreateClient 是一种扩展方法,不能轻易模拟。使用存根要容易得多。

public class MyHttpClientFactory : IHttpClientFactory
{
    public HttpClient CreateClient(string name)
    {
        return new HttpClient();
    }
}

根据您的代码,您可能无法将 MyMyHttpClientFactory 注入模型。但是你应该考虑重构以使其更易于测试。

我没有在 .NET 5 中得到 HttpConfiguration 所以我通过删除对 HttpConfiguration 的需求解决了这个问题:

private LoginController GetLoginController()
{
    var expected = "Hello world";
    var mockFactory = new Mock<IHttpClientFactory>();

    var mockMessageHandler = new Mock<HttpMessageHandler>();
    mockMessageHandler.Protected()
        .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
        .ReturnsAsync(new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StringContent(expected)
        });

    var httpClient = new HttpClient(mockMessageHandler.Object);

    mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);

    var logger = Mock.Of<ILogger<LoginController>>();

    var controller = new LoginController(logger, mockFactory.Object);

    return controller;
}