【问题标题】:Unit testing method with async异步单元测试方法
【发布时间】:2020-07-14 15:11:55
【问题描述】:

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

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

当我执行我的测试用例时,该方法不会返回任何内容。当然,我做错了什么。请帮我找到它。

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

我确实检查了其他答案,例如 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);
        }
    }

【问题讨论】:

  • 您可以将单元测试代码添加到您的帖子中吗?

标签: unit-testing asynchronous moq


【解决方案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()。

【讨论】:

  • 感谢您向我介绍了一个新概念。在我的例子中,类本身的构造函数创建了一个类。所以这似乎对我不起作用。但再次感谢您介绍这一点。
  • 将您的代码添加到您的帖子中,人们将能够更好地帮助您。
猜你喜欢
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2017-12-21
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多