异步单元测试方法

Unit testing method with async

我正在为使用 Moq 框架的方法编写单元测试。

该方法调用了System.Net.Http的方法Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)await

当我执行我的测试用例时,该方法没有 return 任何东西。当然,我做错了什么。请帮我找到它。

请注意,此调用不是松耦合的。

我确实检查了像 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);
        }
    }

你想嘲笑 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()