Skip to content

Instantly share code, notes, and snippets.

@mauricedb
Created May 20, 2013 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauricedb/5612901 to your computer and use it in GitHub Desktop.
Save mauricedb/5612901 to your computer and use it in GitHub Desktop.
Utility class for test enabling the System.Net.Http.HttpClient
public class TestingDelegatingHandler<T> : DelegatingHandler
{
private Func<HttpRequestMessage, HttpResponseMessage> _httpResponseMessageFunc;
public TestingDelegatingHandler(T value)
: this(HttpStatusCode.OK, value)
{ }
public TestingDelegatingHandler(HttpStatusCode statusCode)
: this(statusCode, default(T))
{ }
public TestingDelegatingHandler(HttpStatusCode statusCode, T value)
{
_httpResponseMessageFunc = request => request.CreateResponse(statusCode, value);
}
public TestingDelegatingHandler(
Func<HttpRequestMessage, HttpResponseMessage> httpResponseMessageFunc)
{
_httpResponseMessageFunc = httpResponseMessageFunc;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() => _httpResponseMessageFunc(request));
}
}
[TestMethod]
public void WhenGettingAllBooksTheyShouldBeReturned()
{
// Arrange
var books = new[]
{
new Book{Id = 1, Author = "Me", Title = "Book 1"},
new Book{Id = 2, Author = "You", Title = "Book 2"}
};
var testingHandler = new TestingDelegatingHandler<Book[]>(books);
var server = new HttpServer(new HttpConfiguration(), testingHandler);
var client = new BooksClient(new HttpClient(server));
// Act
var booksReturned = client.GetBooks();
// Assert
Assert.AreEqual(2, booksReturned.Count());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment