Created
July 28, 2021 17:02
-
-
Save ritasker/e842f0b7a6e4d94a7969625c2c0331a3 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Net.Http; | |
using System.Text.Json; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.VisualStudio.Services.Common; | |
namespace Pier8Software.TestingHelpers | |
{ | |
public class MockHttpMessageHandler : HttpMessageHandler | |
{ | |
private readonly string response; | |
private readonly HttpStatusCode statusCode; | |
private readonly Dictionary<string, HttpResponseMessage> responses = new Dictionary<string, HttpResponseMessage>(); | |
private readonly Dictionary<string, HttpRequestMessage> requests = new Dictionary<string, HttpRequestMessage>(); | |
public void AddResponse(HttpMethod method, string endpoint, HttpResponseMessage response) | |
{ | |
var key = GetKey(method, endpoint); | |
responses.Add(key, response); | |
} | |
public async Task ValidateRequest<T>(HttpMethod method, string endpoint, Action<T> assert, JsonSerializerOptions serializerOptions) | |
{ | |
var key = GetKey(method, endpoint); | |
requests.TryGetValue(key, out var request); | |
if (request != null) | |
{ | |
var content = await request.Content.ReadAsStringAsync(); | |
var model = JsonSerializer.Deserialize<T>(content, serializerOptions); | |
assert(model); | |
return; | |
} | |
throw new Exception($"Validation Failed: Request to {endpoint} Not Found."); | |
} | |
public async Task ValidateRequest<T>(HttpMethod method, string endpoint, Action<T> assert) | |
{ | |
await ValidateRequest<T>(method, endpoint, assert, new JsonSerializerOptions()); | |
} | |
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, | |
CancellationToken cancellationToken) | |
{ | |
var key = GetKey(request.Method, request.RequestUri.AbsolutePath); | |
requests[key] = request; | |
if (responses.TryGetValue(key, out var response)) | |
{ | |
return response; | |
} | |
} | |
private string GetKey(HttpMethod method, string endpoint) | |
{ | |
return $"{method.Method}-{endpoint}"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment