我对测试很陌生。我正试图理解如何才能进行单元测试,因为我并不真的需要实际触发这些服务,但可能会嘲笑每个步骤。
如何对以下代码进行单元测试?
public void myFunction()
{
// I am getting an auth token from a service
// then
using (HttpClient httpClient = new HttpClient())
{
// do a POST call on another service
var response = httpClient.PostAsync(url, content);
}
}发布于 2022-01-13 06:23:33
非覆盖成员(此处: HttpClient.PostAsync)不能用于安装/验证表达式。
我还试图像您一样模拟HttpClient,并得到了相同的错误消息。
不可覆盖的成员(此处: HttpClient.PostAsync)不能用于安装/验证表达式。
我还试图像您一样模拟HttpClient,并得到了相同的错误消息。
解决方案:与其嘲笑HttpClient,不如嘲笑HttpMessageHandler.
然后给
mockHttpMessageHandler.Object
传递给您的HttpClient,然后将其传递给产品代码类。这是因为HttpClient在引擎盖下使用了HttpMessageHandler:
// Arrange
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK });
var client = new HttpClient(mockHttpMessageHandler.Object);
this._iADLS_Operations = new ADLS_Operations(client);注意:您还需要一个
using Moq.Protected;在你的测试文件顶部。
然后,您可以从测试中调用使用PostAsync的方法,PostAsync将返回HTTP状态OK响应:
var returnedItem = this._iADLS_Operations.MethodThatUsesPostAsync(/*parameter(s) here*/);优点:模仿HttpMessageHandler意味着在产品代码或测试代码中不需要额外的类。
有用的资源:
https://chrissainty.com/unit-testing-with-httpclient/
https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/
发布于 2022-11-15 19:10:36
在模拟安排之后,可以用
mockHttpMessageHandler.Protected().Verify("SendAsync", Times.Once(), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());https://stackoverflow.com/questions/70690533
复制相似问题