无法通过Azure功能(IHttpClientFactory)进行模拟

时间:2019-09-10 08:12:18

标签: c# unit-testing asp.net-core azure-functions moq

在Azure函数中模拟IHttpClientFactory接口时遇到问题。这是我在做什么,我已经触发,一旦收到消息,我就调用API来更新数据。我为此使用SendAsync方法。在编写单元测试用例时,我无法模拟客户端。对于测试,我尝试在构造函数本身中进行get调用,但仍然无法正常工作。 函数类

 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

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

1 个答案:

答案 0 :(得分:2)

对于嘲笑/拦截<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="us-ascii"/> <xsl:strip-space elements="*"/> <xsl:template match="addRequest"> <xsl:apply-templates select="attributes"/><xsl:text>&#xd;</xsl:text><xsl:text>&#xa;</xsl:text> </xsl:template> <xsl:template match="attributes"> <xsl:value-of select="distinct-values(attr[@name='GPEIEnsDiv']/value/substring-before(.,'$'))" separator=","/> <xsl:text>&#10;</xsl:text> </xsl:template> </xsl:stylesheet> 的用法,我建议您使用mockhttp 您的测试将是:

HttpClient

您可以进一步配置HTTP请求期望的行为,但是为此您应该阅读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); }

的文档。