Last active
February 12, 2019 10:49
-
-
Save jmcd/d4d3f6c31624b3e75ca1a1b6dac9be15 to your computer and use it in GitHub Desktop.
TestHttpClientFactory for unit tests
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
var testHttpClientFactory = new TestHttpClientFactory() | |
.When(r => r.RequestUri.AbsolutePath == "/foobar", r => new HttpResponseMessage(HttpStatusCode.Redirect)) | |
.When(r => true, r => new HttpResponseMessage(HttpStatusCode.NotFound)); | |
// run some tests | |
// check results | |
var logItem = testHttpClientFactory.Log.SingleOrDefault(tpl => tpl.request.RequestUri.Host == "example.com"); | |
Assert.Equal(HttpStatusCode.Whatever, logItem.response.StatusCode); |
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 TestHttpClientFactory : IHttpClientFactory | |
{ | |
private class MockHttpMessageHandler : HttpMessageHandler | |
{ | |
public readonly IList<(Predicate<HttpRequestMessage> predicate, Func<HttpRequestMessage, HttpResponseMessage> factory)> Behaviours = | |
new List<(Predicate<HttpRequestMessage> predicate, Func<HttpRequestMessage, HttpResponseMessage> factory)>(); | |
public readonly IList<(HttpRequestMessage, HttpResponseMessage)> Log = new List<(HttpRequestMessage, HttpResponseMessage)>(); | |
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
var httpResponseMessage = Behaviours.First(b => b.predicate(request)).factory(request); | |
Log.Add((request, httpResponseMessage)); | |
return Task.FromResult(httpResponseMessage); | |
} | |
} | |
private readonly MockHttpMessageHandler handler; | |
private readonly HttpClient client; | |
public TestHttpClientFactory() | |
{ | |
handler = new MockHttpMessageHandler(); | |
client = new HttpClient(handler); | |
} | |
public TestHttpClientFactory When(Predicate<HttpRequestMessage> predicate, Func<HttpRequestMessage, HttpResponseMessage> factory) | |
{ | |
handler.Behaviours.Add((predicate, factory)); | |
return this; | |
} | |
public HttpClient CreateClient(string name) => client; | |
public IList<(HttpRequestMessage request, HttpResponseMessage response)> Log => handler.Log.ToImmutableList(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment