使用超时进行单元测试HttpClient

4
我将创建一个新的Xamarin应用程序,并由于客户的需求,我需要在几乎所有内容上创建单元测试。
在我的应用程序中,我正在使用HttpClient,并且必须设置Timeout,因为该应用程序必须上传图像。但是,如何为HttpClient.Timeout创建单元测试?
除此之外,其他所有内容都是使用HttpMessageHandler模拟的,但是在其中插入Task.Delay对其没有影响。
编辑 添加了代码以澄清。
public async Task ExecuteAsync_NotExecutedWithinTimeout_ThrowsExecption()
{
   // Arrange
   var endpoint = "http://google.dk/";
   var method = HttpMethod.Get;
   var timeoutClient = TimeSpan.FromMilliseconds(2);
   var timeoutServer = TimeSpan.FromMilliseconds(10);
   var requestor = new Requestor(new MessageHandler { Method = HttpMethod.Get, Timeout = timeoutServer, URL = url });
   bool result = false;

   // Act
   try
   {
      await requestor.ExecuteAsync(method, endpoint, timeout: timeoutClient);
   }
   catch (TimeoutException)
   {
      result = true;
   }

   // Assert
   Assert.AreEqual(true, result);
}

class MessageHandler : HttpMessageHandler
{
   public TimeSpan? TimeOut { get; set; }

   protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   {
      if (Timeout.HasValue)
         await Task.Delay(Timeout.Value);

      return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
   }
}

class Requestor
{
   public async Task<string> ExecuteAsync(HttpMethod httpMethod, string endpoint, TimeSpan? timeout = default(TimeSpan?))
   {
      using (var client = GetHttpClient())
      {
         if (timeout.HasValue)
         {
            client.Timeout = timeout.Value;
         }
         var response = await client.GetAsync(endpoint);
      }
   }
}

private HttpClient GetHttpClient()
{
    var client = _messageHandler == null ? new HttpClient() : new HttpClient(_messageHandler, false);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    return client;
}

问题出在哪里?您能给我们展示一些代码吗? - YuvShap
我现在添加了一些代码。 - Lasse Madsen
请参考以下这些问题: https://dev59.com/aFoV5IYBdhLWcg3wTdQc https://dev59.com/_Wgv5IYBdhLWcg3wTvHL - YuvShap
抱歉,我忘记了 GetHttpClient 方法。 - Lasse Madsen
你正在使用 HttpClient 类的具体实例,这会使你的代码难以测试,请参考上面的链接了解如何模拟 HttpClient 类。 - YuvShap
显示剩余3条评论
1个回答

5

替代

if (Timeout.HasValue)
         await Task.Delay(Timeout.Value);

使用

throw new TimeoutException()

谢谢Yuri。这正是我在寻找的。 - Lasse Madsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接