【问题标题】:Unit testing HttpClient with timeout使用超时对 HttpClient 进行单元测试
【发布时间】:2017-03-03 12:23:11
【问题描述】:

我打算在 Xamarin 中创建一个新应用,由于客户的需求,我需要对几乎所有内容进行单元测试。

在我的应用程序中,我使用的是 HttpClient,我必须设置超时,因为应用程序必须上传图像。
但是如何为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;
}

【问题讨论】:

标签: c# unit-testing xamarin


【解决方案1】:

代替

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

使用

throw new TimeoutException()

【讨论】:

  • 谢谢尤里。这正是我想要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2018-05-21
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多