首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟Azure函数失败(IHttpClientFactory)

模拟Azure函数失败(IHttpClientFactory)
EN

Stack Overflow用户
提问于 2019-09-10 16:12:19
回答 1查看 631关注 0票数 1

我在模拟Azure函数中的IHttpClientFactory接口时遇到了一些问题。下面是我正在做的事情,我有触发器,一旦收到消息,我正在调用API来更新数据。为此,我使用了SendAsync方法。在编写单元测试用例时,我无法模拟client.For测试,我尝试在构造函数本身中进行get调用,但仍然不起作用。函数类

代码语言:javascript
复制
 public class UpdateDB
{
    private readonly IHttpClientFactory _clientFactory;
    private readonly HttpClient _client;

    public UpdateDB(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
        _client = clientFactory.CreateClient();
        _client.GetAsync("");
    }

    [FunctionName("DB Update")]
    public async Task Run([ServiceBusTrigger("topic", "dbupdate", Connection = "connection")]string mySbMsg, ILogger log)
    {
        var client = _clientFactory.CreateClient();
        log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
        DBConvert payload = JsonConvert.DeserializeObject<DBConvert>(mySbMsg);
        string jsonContent = JsonConvert.SerializeObject(payload);
        var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
        HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, "api/DBU/data");
        message.Content = httpContent;
        var response = await client.SendAsync(message);
    }
}

TestClass

代码语言:javascript
复制
namespace XUnitTestProject1
{
    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 class test
    {
        [Fact]
        public async Task Should_Return_Ok()
        {
            //
            Mock<ILogger> _logger = new Mock<ILogger>();
            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.Accepted);
                return Task.FromResult(response);
            });
            var client = new HttpClient(clientHandlerStub);

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

            var clientTest = mockFactory.Object.CreateClient();

            //Works Here, but not in the instance.
            clientTest.GetAsync("");

            IHttpClientFactory factory = mockFactory.Object;

            var service = new UpdateDB(factory);

            await service.Run("", _logger.Object);

        }
    }
}

我已经遵循了这里的示例。How to mock the new HttpClientFactory in .NET Core 2.1 using Moq

EN

回答 1

Stack Overflow用户

发布于 2019-09-10 16:58:06

为了模拟/拦截HttpClient的使用,我建议您使用mockhttp,然后您的测试将是:

代码语言:javascript
复制
class Test {
  private readonly Mock<IHttpClientFactory> httpClientFactory;
  private readonly MockHttpMessageHandler handler;

  constructor(){
    this.handler = new MockHttpMessageHandler();
    this.httpClientFactory = new Mock<IHttpClientFactory>();
    this.httpClientFactory.Setup(_ => _.CreateClient(It.IsAny<string>()))
        .Returns(handler.ToHttpClient());
  }

  [Fact]
  public async Task Test(){
    // Arrange
    this.handler.Expect("api/DBU/data")
                .Respond(HttpStatusCode.Ok);
    var sut = this.CreateSut();

    // Act
    await sut.Run(...);

    // Assert
    this.handler.VerifyNoOutstandingExpectation();       
  }

  private UpdateDB CreateSut() => new UpdateDB(this.httpClientFactory.Object);
}

您可以进一步配置HTTP请求期望的行为方式,但为此,您应该阅读一点mockhttp文档

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57866581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档