public async Task <TResponse> InvokeMethodAsync <TPayload, TResponse>(string endpointUrl, HttpMethod method, TPayload body) { var message = _messageCreator.CreateMessage(method, endpointUrl); if (body != null) { string json = JsonConvert.SerializeObject(body, Formatting.None, _serializeSettings); message.Content = new StringContent(json, Encoding.UTF8, "application/json"); } var response = await _cmHttpClient.SendAsync(message); return(await ReadResultAsync <TResponse>(response)); }
public async Task <HttpResponseMessage> SendAsync(HttpRequestMessage message) { var isFirst = _firstRequest; _firstRequest = false; var serializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented }; var serializedRequest = MakeProjectAgnostic(JsonConvert.SerializeObject(message, serializationSettings)); var serializedRequestContent = await SerializeContent(message.Content); var hashContent = $"{message.Method} {serializedRequest} {UnifySerializedRequestContent(serializedRequestContent)}"; var folderPath = GetMockFileFolder(message, hashContent); if (_saveToFileSystem) { if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } else if (isFirst) { // Cleanup previously recorded data at first request to avoid data overlap upon change Directory.Delete(folderPath, true); } var response = await _nativeClient.SendAsync(message); File.WriteAllText(Path.Combine(folderPath, "request.json"), serializedRequest); File.WriteAllText(Path.Combine(folderPath, "request_content.json"), serializedRequestContent); var serializedResponse = MakeProjectAgnostic(JsonConvert.SerializeObject(response, serializationSettings)); var serializedResponseContent = await SerializeContent(response.Content); File.WriteAllText(Path.Combine(folderPath, "response.json"), serializedResponse); File.WriteAllText(Path.Combine(folderPath, "response_content.json"), serializedResponseContent); return(response); } else { // Expected request is validated through the presence of the recorded files Assert.True( Directory.Exists(folderPath), $"Cannot find expected data folder {folderPath} for {message.Method} request to {message.RequestUri}. " + Environment.NewLine + $"Either the request properties or content seem to differ from the expected recorded state." + Environment.NewLine + $"Request:" + Environment.NewLine + serializedRequest + Environment.NewLine + $"Request content:" + Environment.NewLine + serializedRequestContent ); var serializedResponse = ApplyProjectData(File.ReadAllText(Path.Combine(folderPath, "response.json"))); var serializedResponseContent = File.ReadAllText(Path.Combine(folderPath, "response_content.json")); var deserializationSettings = new JsonSerializerSettings { ContractResolver = new IgnoreHttpContentContractResolver() }; var response = JsonConvert.DeserializeObject <HttpResponseMessage>(serializedResponse, deserializationSettings); response.Content = new StringContent(serializedResponseContent); return(response); } }