64 lines
1.8 KiB
C#
64 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
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>();
|
|
private HttpStatusCode _fallbackCode = HttpStatusCode.OK;
|
|
|
|
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 HttpClientBuilder WithErrorStatus(HttpStatusCode statusCode) {
|
|
_fallbackCode = statusCode;
|
|
return this;
|
|
}
|
|
|
|
public HttpClient Build(out MockHttpMessageHandler mockHttpMessageHandler) {
|
|
mockHttpMessageHandler = new MockHttpMessageHandler();
|
|
|
|
mockHttpMessageHandler.Fallback.Respond(_fallbackCode, message => message.Content = new StringContent(string.Empty));
|
|
|
|
var mockedRequest = mockHttpMessageHandler.Expect(_method, _url).Respond("application/json", _response ?? string.Empty);
|
|
|
|
if (_queries.Any())
|
|
mockedRequest.WithExactQueryString(_queries);
|
|
if (!string.IsNullOrEmpty(_body) || _method == HttpMethod.Post)
|
|
mockedRequest.WithContent(_body ?? string.Empty);
|
|
|
|
var httpClient = mockHttpMessageHandler.ToHttpClient();
|
|
httpClient.BaseAddress = new Uri("http://example.com");
|
|
return httpClient;
|
|
}
|
|
|
|
public HttpClient Build() => Build(out _);
|
|
}
|
|
}
|