Skip to content

Instantly share code, notes, and snippets.

@bryanwood
Created March 7, 2014 06:11
Show Gist options
  • Save bryanwood/9406178 to your computer and use it in GitHub Desktop.
Save bryanwood/9406178 to your computer and use it in GitHub Desktop.
HttpClient with handler for testing
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
var http = new HttpClient(new FakeHandler());
http.BaseAddress = new Uri("http://example.com");
var result = http.GetStringAsync("/").Result;
Console.WriteLine(result);
Console.ReadLine();
}
}
public class FakeHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Sup")
};
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment