using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using RichardSzalay.MockHttp; namespace Website.Tests { public class HttpClientBuilder { private string _url, _response, _body; private HttpMethod _method; private readonly Dictionary _queries = new Dictionary(); public HttpClientBuilder WithUrl(string url) { _url = url; return this; } public HttpClientBuilder WithResponse(string response) { _response = response; return this; } public HttpClientBuilder WithMethod(HttpMethod method) { _method = method; return this; } public HttpClientBuilder WithQueryString(string key, string value) { _queries.Add(key, value); return this; } public HttpClientBuilder WithPostBody(string body) { _body = body; return this; } public HttpClient Build() { var httpMessageHandler = new MockHttpMessageHandler(); var mockedRequest = httpMessageHandler.Expect(_method, _url).Respond("application/json", _response ?? string.Empty); if (_queries.Any()) mockedRequest.WithExactQueryString(_queries); if (!string.IsNullOrEmpty(_body)) mockedRequest.WithContent(_body); var httpClient = httpMessageHandler.ToHttpClient(); httpClient.BaseAddress = new Uri("http://example.com"); return httpClient; } } }