模拟IHttpClientFactory-xUnit C#

问题描述 投票:0回答:1

我正在尝试在我的项目(带有.net core 2.1的c#)中构建通用HTTP服务,并且已经按照下面的代码片段HttpService进行了此操作。

我还通过从我的业务逻辑类中调用它来开始使用它,该逻辑类使用此通用PostAsync方法将HTTP调用发布到正文中包含内容的第三方。它运行完美。

但是,当我尝试对其进行测试时,我失败了!实际上,当我尝试调试(测试模式)时,即使在使用伪造对象和模拟的情况下,调试器到达业务类null的这一行var result = await _httpService.PostAsync("https://test.com/api", content);时,我也会收到Processor响应,尽管它通常在调试模式下无需测试/模拟即可工作。

HTTP服务:

public interface IHttpService
{
    Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content);
}

public class HttpService : IHttpService
{
    private readonly IHttpClientFactory _httpClientFactory;

    public HttpService(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
    {
        var httpClient = _httpClientFactory.CreateClient();
        httpClient.Timeout = TimeSpan.FromSeconds(3);
        var response = await httpClient.PostAsync(requestUri, content).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();

        return response;
    }
}

商务舱:

public class Processor : IProcessor
{
    private readonly IHttpService _httpService;

    public Processor() { }

    public Processor(IHttpService httpService, IAppSettings appSettings)
    {
        _httpService = httpService;
    }

    public async Task<HttpResponseMessage> PostToVendor(Order order)
    {
        // Building content
        var json = JsonConvert.SerializeObject(order, Formatting.Indented);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        // HTTP POST
        var result = await _httpService.PostAsync("https://test.com/api", content); // returns null during the test without stepping into the method PostAsyn itself

        return result;
    }
}

测试类:

public class MyTests
{
    private readonly Mock<IHttpService> _fakeHttpMessageHandler;
    private readonly IProcessor _processor; // contains business logic
    private readonly Fixture _fixture = new Fixture();

    public FunctionTest()
    {
        _fakeHttpMessageHandler = new Mock<IHttpService>();
        _processor = new Processor(_fakeHttpMessageHandler.Object);
    }

    [Fact]
    public async Task Post_To_Vendor_Should_Return_Valid_Response()
    {
        var fakeHttpResponseMessage = new Mock<HttpResponseMessage>(MockBehavior.Loose, new object[] { HttpStatusCode.OK });

        var responseModel = new ResponseModel
        {
            success = true,
            uuid = Guid.NewGuid().ToString()
        };

        fakeHttpResponseMessage.Object.Content = new StringContent(JsonConvert.SerializeObject(responseModel), Encoding.UTF8, "application/json");

        var fakeContent = _fixture.Build<DTO>().Create(); // DTO is the body which gonna be sent to the API
        var content = new StringContent(JsonConvert.SerializeObject(fakeContent), Encoding.UTF8, "application/json");

        _fakeHttpMessageHandler.Setup(x => x.PostAsync(It.IsAny<string>(), content))
            .Returns(Task.FromResult(fakeHttpResponseMessage.Object));

        var res = _processor.PostToVendor(fakeContent).Result;
        Assert.NotNull(res.Content);
        var actual = JsonConvert.SerializeObject(responseModel);
        var expected = await res.Content.ReadAsStringAsync();
        Assert.Equal(expected, actual);
    }
}
c# httpclient xunit fixtures httpclientfactory
1个回答
1
投票

您的问题是在模拟设置中:

_fakeHttpMessageHandler.Setup(x => x.PostAsync(It.IsAny<string>(), content))
        .Returns(Task.FromResult(fakeHttpResponseMessage.Object));

PostAsync方法的第二个参数应该是content,但是由于StringContent是引用类型,因此在模拟中设置的content与在处理器中创建的content不同。如果将其更改为下一个,它应该可以按预期工作:

    _fakeHttpMessageHandler.Setup(x => x.PostAsync(It.IsAny<string>(), It.IsAny<StringContent>()))
        .Returns(Task.FromResult(fakeHttpResponseMessage.Object));

P.S。对PostAsync的null响应表示该方法具有默认设置,这意味着它将返回默认值

© www.soinside.com 2019 - 2024. All rights reserved.