Exemple #1
0
        /// <summary>
        /// Sets expectations on the response of a mocked <c>HttpClient</c>
        /// </summary>
        /// <param name="expectedResponseContent">The expected content in the HTTP response body</param>
        /// <param name="expectedStatusCode">The expected HTTP Status Code</param>
        /// <returns></returns>
        public HttpClientMocker ResponseShouldBe(string expectedResponseContent, HttpStatusCode expectedStatusCode = HttpStatusCode.OK)
        {
            var handler = new HttpMessageHandlerStub(async(request, cancellationToken) =>
            {
                foreach (var condition in _conditions)
                {
                    if (!condition(request))
                    {
                        return(await Task.FromResult(new HttpResponseMessage
                        {
                            Content = new ByteArrayContent(new byte[] { })
                        }));
                    }
                }

                var responseMessage = new HttpResponseMessage(expectedStatusCode)
                {
                    Content = expectedResponseContent != null ? new StringContent(expectedResponseContent)
                    : new ByteArrayContent(new byte[] { })
                };

                return(await Task.FromResult(responseMessage));
            });

            _httpClientWithExpectationsBuilder.MessageHandler = handler;
            return(_httpClientWithExpectationsBuilder);
        }
Exemple #2
0
        /// <summary>
        /// Creates a mocked <c>HttpClient</c> with the conditions and expectations set.
        /// If no conditions and expectations are set, a default mock is created with
        /// no conditions and expectations.
        /// </summary>
        /// <returns>A mocked <c>HttpClient</c></returns>
        public HttpClient Build()
        {
            if (MessageHandler == null)
            {
                MessageHandler = new HttpMessageHandlerStub();
            }
            var httpClient = new HttpClient(MessageHandler);

            if (_baseAddress != null)
            {
                httpClient.BaseAddress = new Uri(_baseAddress);
            }

            return(httpClient);
        }