Check the value of HttpRequestMessage.Content after calling PostAsync

We scoffed at HttpMessageHandler, so we can test the class that uses HttpClient.

One of our test methods creates a new one HttpClient, calls PostAsyncand provides HttpClient. We would like to test the ContentHTTP request as follows:

Assert.Equal("", ActualHttpRequestMessage.Content.ReadAsStringAsync());

The problem is that we cannot access the remote object because it uses . HttpClientContent

Question How can we check the contents?

This is our Moq installation.

MockHttpMessageHandler = new Mock<HttpMessageHandler>();

MockHttpMessageHandler
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.IsAny<HttpRequestMessage>(),
        ItExpr.IsAny<CancellationToken>())
    .Callback<HttpRequestMessage, CancellationToken>(
        (httpRequestMessage, cancellationToken) =>
        {
            ActualHttpRequestMessage = httpRequestMessage;
        })
    .Returns(
        Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(string.Empty)
        }));

So we use it in the tested class.

new HttpClient(HttpMessageHandler);
+4
1

:

MockHttpMessageHandler
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.IsAny<HttpRequestMessage>(),
        ItExpr.IsAny<CancellationToken>())
    .Callback<HttpRequestMessage, CancellationToken>(
        (httpRequestMessage, cancellationToken) =>
        {
            // +++++++++++++++++++++++++++++++++++++++++
            // Read the Content here before it disposed
            ActualHttpRequestContent = httpRequestMessage.Content
                .ReadAsStringAsync()
                .GetAwaiter()
                .GetResult();

            ActualHttpRequestMessage = httpRequestMessage;
        })
    .Returns(
        Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(string.Empty)
        }));

:

Assert.Equal("", ActualHttpRequestContent);

, Content , , , . .

+2

Source: https://habr.com/ru/post/1667211/


All Articles