在决定我要发回什么样的响应进行测试之前,有没有办法获取 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;
}
}