我正在为使用Moq
框架的方法编写单元测试。
该方法使用Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
调用System.Net.Http
的方法await
。
当我执行测试用例时,该方法不返回任何内容。当然,我做错了。请帮我找到它。
请注意,此呼叫并非松耦合。
我确实检查了诸如Unit testing async method - test never completes之类的其他答案,这些答案具有松散的耦合性并且可以被嘲笑。
编辑1 : 与我尝试进行单元测试类似的方法
class Class1
{
public async Task<string> Method(string url)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,url);
HttpResponseMessage response = await new HttpClient().SendAsync(request);
return System.Convert.ToString( response);
}
}
答案 0 :(得分:1)
您是否要嘲笑HttpClient
?如果是这样,则不建议这样做;而不是模拟HttpClient
实例化真实的HttpClient
,而是将模拟的HttpMessageHandler
传递给构造函数。
来源:https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/
编辑:要读取HTTP响应的内容,您需要调用response.Content.ReadAsStringAsync()
方法而不是.ToString()
。