Lasse Madsen
Lasse Madsen

Reputation: 602

Unit testing HttpClient with timeout

I am going to create a new app in Xamarin, and due to demands from the customer, I need to create unit test on almost everything.

In my app I am using a HttpClient, and I have to set Timeout, as the app has to upload images.
But how can I make unit tests for HttpClient.Timeout?

Everything else is mocked up using HttpMessageHandler, but inserting a Task.Delay in there does not affect it.

EDIT
Added code for clarification

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;
}

Upvotes: 4

Views: 8476

Answers (1)

Yuri S
Yuri S

Reputation: 5370

Instead of

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

use

throw new TimeoutException()

Upvotes: 5

Related Questions