Utility class for test enabling the System.Net.Http.HttpClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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