Put in test fallback for manual error code. Output http mock for later verification.

This commit is contained in:
Robert Marshall 2020-04-11 09:27:27 +01:00
parent 022de696e3
commit e389b2404a
2 changed files with 26 additions and 11 deletions

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using RichardSzalay.MockHttp;
@ -9,6 +10,7 @@ namespace Website.Tests {
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;
@ -35,19 +37,28 @@ namespace Website.Tests {
return this;
}
public HttpClient Build() {
var httpMessageHandler = new MockHttpMessageHandler();
public HttpClientBuilder WithErrorStatus(HttpStatusCode statusCode) {
_fallbackCode = statusCode;
return this;
}
var mockedRequest = httpMessageHandler.Expect(_method, _url).Respond("application/json", _response ?? string.Empty);
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))
mockedRequest.WithContent(_body);
if (!string.IsNullOrEmpty(_body) || _method == HttpMethod.Post)
mockedRequest.WithContent(_body ?? string.Empty);
var httpClient = httpMessageHandler.ToHttpClient();
var httpClient = mockHttpMessageHandler.ToHttpClient();
httpClient.BaseAddress = new Uri("http://example.com");
return httpClient;
}
public HttpClient Build() => Build(out _);
}
}