【问题标题】:Mocking HttpMessageHandler with moq - How do I get the contents of the request?使用 moq 模拟 HttpMessageHandler - 如何获取请求的内容?
【发布时间】:2021-04-01 10:54:32
【问题描述】:

在决定我要发回什么样的响应进行测试之前,有没有办法获取 http 请求的内容?多个测试将使用此类,并且每个测试将有多个 http 请求。此代码无法编译,因为 lambda 不是异步的,并且其中有一个 await。我是 async-await 的新手,所以我不确定如何解决这个问题。我曾短暂地考虑过拥有多个 TestHttpClientFactories,但这意味着重复的代码,所以如果可能的话,决定反对它。任何帮助表示赞赏。

public class TestHttpClientFactory : IHttpClientFactory
{
    public HttpClient CreateClient(string name)
    {
        var messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

        messageHandlerMock.Protected()
            .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
            .ReturnsAsync((HttpRequestMessage request, CancellationToken token) =>
            {
                HttpResponseMessage response = new HttpResponseMessage();
                var requestMessageContent = await request.Content.ReadAsStringAsync();

                // decide what to put in the response after looking at the contents of the request

                return response;
            })
            .Verifiable();

        var httpClient = new HttpClient(messageHandlerMock.Object);
        return httpClient;
    }
}

【问题讨论】:

  • 创建您自己的处理程序,公开委托以处理所需的行为
  • 恩科西,这是个好主意。如果起订量不起作用,我一定会考虑的。
  • 我还应该提到我尝试过 var requestMessageContent = request.Content.ToString();但得到了 System.NullReferenceException,所以这不是解决方案。
  • 看看我对类似问题的回答stackoverflow.com/a/54227679/5233410

标签: asp.net async-await integration-testing moq httpcontent


【解决方案1】:

要利用异步委托,请改用Returns 方法

public class TestHttpClientFactory : IHttpClientFactory {
    public HttpClient CreateClient(string name) {
        var messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

        messageHandlerMock.Protected()
            .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
            .Returns(async (HttpRequestMessage request, CancellationToken token) => {
                
                string requestMessageContent = await request.Content.ReadAsStringAsync();

                HttpResponseMessage response = new HttpResponseMessage();

                //...decide what to put in the response after looking at the contents of the request

                return response;
            })
            .Verifiable();

        var httpClient = new HttpClient(messageHandlerMock.Object);
        return httpClient;
    }
}

或者考虑创建您自己的处理程序,该处理程序公开一个委托来处理所需的行为。

例如

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 TestHttpClientFactory : IHttpClientFactory {
    public HttpClient CreateClient(string name) {
        var messageHandlerMock = new DelegatingHandlerStub(async (HttpRequestMessage request, CancellationToken token) => {
                
            string requestMessageContent = await request.Content.ReadAsStringAsync();

            HttpResponseMessage response = new HttpResponseMessage();

            //...decide what to put in the response after looking at the contents of the request

            return response;
        });

        var httpClient = new HttpClient(messageHandlerMock);
        return httpClient;
    }
}

【讨论】:

  • 谢谢。我决定对使用 'Returns(async ...' 进行小而有效的改变,效果很好!
猜你喜欢
  • 2020-02-07
  • 2021-12-03
  • 1970-01-01
  • 2012-03-22
  • 2013-01-16
  • 2012-03-18
  • 2010-10-19
  • 2016-09-30
  • 2019-10-06
相关资源
最近更新 更多