我不明白你的意思
http 类型的客户端
但是如果像示例中一样,您想测试一个使用 HttpClient 的类,您可以为 HttpClient 创建一个包装器并使用依赖注入传递它的接口(以便您可以模拟它),或者您利用 HttpResponseMessage HttpClient 的构造函数参数。
将 HttpClient 设为构造函数参数,并在测试中创建如下代码:
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(), // Customise this as you want
ItExpr.IsAny<CancellationToken>()
)
// Create the response you want to return
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("[{'prop1': 100,'prop2': 'value'}]"),
});
// Create an HttpClient using the mocked message handler
var httpClient = new HttpClient(mockHttpMessageHandler.Object)
{
BaseAddress = new Uri("http://anyurl.com/"),
};
var testedService = new MyServiceUnderTest(httpClient);
var result = await testedService.MethodUnderTest(parameters [...]);
为了简化起订量的设置,限制预期的 HttpRequestMessage,我使用了这个辅助方法。
/// <summary>
/// Setup the mocked http handler with the specified criteria
/// </summary>
/// <param name="httpStatusCode">Desired status code returned in the response</param>
/// <param name="jsonResponse">Desired Json response</param>
/// <param name="httpMethod">Post, Get, Put ...</param>
/// <param name="uriSelector">Function used to filter the uri for which the setup must be applied</param>
/// <param name="bodySelector">Function used to filter the body of the requests for which the setup must be applied</param>
private void SetupHttpMock(HttpStatusCode httpStatusCode, string jsonResponse, HttpMethod httpMethod, Func<string, bool> uriSelector, Func<string, bool> bodySelector = null)
{
if (uriSelector == null) uriSelector = (s) => true;
if (bodySelector == null) bodySelector = (s) => true;
_messageHandlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync",
ItExpr.Is<HttpRequestMessage>(m =>
m.Method == httpMethod &&
bodySelector(m.Content.ReadAsStringAsync().Result) &&
uriSelector(m.RequestUri.ToString())),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = httpStatusCode,
Content = jsonResponse == null ? null : new StringContent(jsonResponse, Encoding.UTF8, "application/json")
});
}