最小起订量,方法 HttpClient.SendAsync 是 public。怎么修?
Moq, Method HttpClient.SendAsync is public. How to fix?
我收到错误:
System.ArgumentException: Method HttpClient.SendAsync is public. Use strong-typed Expect overload instead:
mock.Setup(x => x.SendAsync());
同时尝试 运行 以下代码:
autoMock.Mock<HttpClient>()
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(httpResponseMessage)
.Verifiable();
我可能在这里遗漏了什么?
- 你需要模拟
HttpRequestHandler
:
(您可能需要将 MockBehavior.Strict
传递给 Mock<T>
ctor)
var mockedHandler = new Mock<HttpMessageHandler>();
- 您需要创建预期的响应:
var expectedResponse = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(@"..."),
};
- 你必须连接东西:
mockedHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(expectedResponse);
- 最后你应该在实例化
HttpClient
实例时传递 mockedHandler
var httpClient = new HttpClient(handlerMock.Object);
MockHttp 库值得一看,它使您的 mocking lot 更容易。
我收到错误:
System.ArgumentException: Method HttpClient.SendAsync is public. Use strong-typed Expect overload instead: mock.Setup(x => x.SendAsync());
同时尝试 运行 以下代码:
autoMock.Mock<HttpClient>()
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(httpResponseMessage)
.Verifiable();
我可能在这里遗漏了什么?
- 你需要模拟
HttpRequestHandler
:
(您可能需要将 MockBehavior.Strict
传递给 Mock<T>
ctor)
var mockedHandler = new Mock<HttpMessageHandler>();
- 您需要创建预期的响应:
var expectedResponse = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(@"..."),
};
- 你必须连接东西:
mockedHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(expectedResponse);
- 最后你应该在实例化
HttpClient
实例时传递mockedHandler
var httpClient = new HttpClient(handlerMock.Object);
MockHttp 库值得一看,它使您的 mocking lot 更容易。