I'm trying to verify the HttpContent
of an HttpRequestMessage
, but reading the content requires an async operation. How can I do this using Moq
?
Illustrative example:
[TestMethod]
public async Task Example()
{
var mockHttpMessageHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHttpMessageHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(""),
})
.Verifiable();
// call some business component that should send the expected JSON via HTTP Post
await ExecuteSomeBusinessComponentThatPostsViaHttp(httpClient);
this.MockHttpMessageHandler.Protected().Verify(
"SendAsync",
Times.Once(),
ItExpr.Is<HttpRequestMessage>(request =>
JToken.DeepEquals(
// the next line does not compile
JToken.Parse(await request.Content.ReadAsStringAsync()),
JObject.FromObject(new { Result = new { Foo = "Bar" } }))),
ItExpr.IsAny<CancellationToken>());
}
How can I get this test to compile? I.e., how can I use await
within an It.Is(...)
expression?
Alternatively, is there some other way to test the http request content?