Home > Software design >  Are there any ways to get/test the actual request body in Mock HttpMessageHandler?
Are there any ways to get/test the actual request body in Mock HttpMessageHandler?

Time:02-10

public async AddName(){   
    var requestUri = "someuri";
    var payload = new AddNameRequest()
            {
                NameParts = new string[] { "Name001" },
                Formula = string.Empty
            };

        // Act
        var responseMessage = await this.httpClient.PostAsJsonAsync(requestUri, payload);
}

And UnitTest for it:

    public async AddName_ExpectedBeh(){
//Create URI
//Create responseMessage
        var mockHandler = new Mock<HttpMessageHandler>();
                    mockHandler.Protected()
                        .Setup<Task<HttpResponseMessage>>(
                        "SendAsync",
                        ItExpr.Is<HttpRequestMessage>(r => r.Method == responseMessage.RequestMessage.Method && r.RequestUri.ToString().EndsWith(responseMessage.RequestMessage.RequestUri.ToString())),
                        ItExpr.IsAny<CancellationToken>())
                        .ReturnsAsync(responseMessage);
        
                    var httpClient = new HttpClient(mockHandler.Object);
//Pass HttpClient to Main Class
//Do Request
//Assert the response
    }

The issue in the previous Unit test is that I'm unable to test payload(request body). I see that mockHandler can read HttpRequestMessage, but I couldn't read it outside of the mockHandler.Setup(). So are there any ways to get/test HttpRequestMessage and how can I do that? For example, I want to check if the request body contains "Name001".

CodePudding user response:

The payload is available in the Setup method. The way you can test it is you can add a method in which you can test what you want with it. For example

public async Task<bool> IsRequestValid(HttpRequestMessage requestMessage)
{
    string stringContent = await requestMessage.Content.ReadAsStringAsync();
    
    // Example of some validation...
    return stringContent.Contains("myProperty");
}

And if this method returns true, the mockHandler will return the desired message, if it's not it will return default (null). This is how you will know that your request is correct. Alternatively, from this method, you can throw exception or Assert.False().

You can append this check in your existing Setup expression with && IsRequestValid(r.Content).

  • Related