4

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; } 
8
  • Where is the problem? Can you show us some code? Commented Oct 21, 2016 at 9:04
  • I added some of the code now. Commented Oct 21, 2016 at 9:17
  • I did not understand how HttpMessageHandler can mock or stub the HttpClient? it's looks like you are using the concrete HttpClient class... Commented Oct 21, 2016 at 9:57
  • please refer these questions stackoverflow.com/questions/36425008/… stackoverflow.com/questions/10693955/… Commented Oct 21, 2016 at 9:58
  • Sorry, I forgot the GetHttpClient method Commented Oct 21, 2016 at 11:07

1 Answer 1

5

Instead of

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

use

throw new TimeoutException() 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Yuri. It was just what I was looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.