使用超时对 HttpClient 进行单元测试

Las*_*sen 4 c# unit-testing xamarin

我将在 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;
}
Run Code Online (Sandbox Code Playgroud)

Yur*_*i S 5

代替

if (Timeout.HasValue)
         await Task.Delay(Timeout.Value);
Run Code Online (Sandbox Code Playgroud)

使用

throw new TimeoutException()
Run Code Online (Sandbox Code Playgroud)