Created
September 2, 2015 12:29
-
-
Save dealproc/f115bc18549642226ed5 to your computer and use it in GitHub Desktop.
Testing Delegating Handler
This file contains hidden or 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
/// <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