Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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