Skip to content

Instantly share code, notes, and snippets.

@dealproc
Created September 2, 2015 12:29
Show Gist options
  • Save dealproc/f115bc18549642226ed5 to your computer and use it in GitHub Desktop.
Save dealproc/f115bc18549642226ed5 to your computer and use it in GitHub Desktop.
Testing Delegating Handler
/// <summary>
/// From: http://blogs.msmvps.com/theproblemsolver/2013/05/20/unit-testing-code-depending-on-the-asp-net-webapi-httpclient/
/// </summary>
/// <typeparam name="T"></typeparam>
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 => new HttpResponseMessage(statusCode) {
Content = new StringContent(JsonConvert.SerializeObject(value), System.Text.Encoding.UTF8, "application/json")
};
}
public TestingDelegatingHandler(Func<HttpRequestMessage, HttpResponseMessage> httpResponseMessageFunc) {
_httpResponseMessageFunc = httpResponseMessageFunc;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
return Task.Factory.StartNew(() => _httpResponseMessageFunc(request));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment