website/Website.Tests/HttpClientBuilder.cs

53 lines
1.3 KiB
C#

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<string, string> _queries = new Dictionary<string, string>();
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;
}
}
}