-1

更新:

完整的代码示例:

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

4

2 回答 2

1

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

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

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

于 2021-02-17T09:10:11.833 回答
0

我没有进去HttpConfiguration.NET 5所以我通过消除对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;
}
于 2021-02-18T08:17:26.340 回答