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".