public async void GivenRequestDoesNotMatchVerification_WhenVerificationIsAttempted_ThenVerificationSuceeds()
        {
            var path        = "/bodytest456";
            var requestBody = "This is the request body 456";

            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("http://localhost:1080/");

                var expectedRequest = RequestBuilder.Request()
                                      .WithMethod(HttpMethod.Post)
                                      .WithPath(path)
                                      .WithBody(requestBody);
                var mockServerClient = new MockServerClient(httpClient);
                mockServerClient.When(expectedRequest)
                .Respond(ResponseBuilder.Respond().WithStatusCode(200));

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "/bodytestfourfivesix");
                httpRequestMessage.Content = new StringContent(requestBody, System.Text.Encoding.UTF8);
                var response = await httpClient.SendAsync(httpRequestMessage);

                var result = await mockServerClient.Verify(expectedRequest.Create(), new VerificationTimes(1, 1));

                Assert.False(result);
            }
        }
Example #2
0
 private async Task SetupResponseBodyExpectation(BodyContent bodyContent)
 {
     await MockServerClient
     .When(Request()
           .WithMethod(HttpMethod.Get),
           Times.Unlimited())
     .RespondAsync(Response()
                   .WithStatusCode(200)
                   .WithBody(bodyContent)
                   .WithDelay(TimeSpan.Zero)
                   );
 }
Example #3
0
        public void ShouldClearExpectation()
        {
            // arrange
            HttpRequest request = Request().WithMethod("GET").WithPath("/hello");

            mockServerClient
            .When(request, Times.Unlimited())
            .Respond(Response().WithStatusCode(200).WithBody("hello").WithDelay(TimeSpan.FromSeconds(0)));

            // act 1
            string         responseBody = null;
            HttpStatusCode?statusCode   = null;

            SendRequest(BuildGetRequest("/hello"), out responseBody, out statusCode);

            // assert
            Assert.Equal(HttpStatusCode.OK, statusCode.Value);
            Assert.Equal("hello", responseBody);

            // act 2
            mockServerClient.Clear(request);

            SendRequest(BuildGetRequest("/hello"), out responseBody, out statusCode);

            // assert
            Assert.Equal(HttpStatusCode.NotFound, statusCode.Value);
        }
Example #4
0
        private void SendHello(int times)
        {
            var request = Request().WithMethod(HttpMethod.Get).WithPath("/hello");

            MockServerClient
            .When(request, Times.Unlimited())
            .Respond(Response().WithStatusCode(200).WithBody("hello").WithDelay(TimeSpan.FromSeconds(0)));

            for (var i = 0; i < times; i++)
            {
                SendRequest(BuildGetRequest("/hello"), out _, out _);
            }
        }
 private async Task SetupRequestBodyExpectation(BodyMatcher requestBody)
 {
     await MockServerClient
     .When(Request()
           .WithMethod(HttpMethod.Post)
           .WithBody(requestBody),
           Times.Unlimited())
     .RespondAsync(Response()
                   .WithStatusCode(200)
                   .WithBody("response")
                   .WithDelay(TimeSpan.Zero)
                   );
 }
        private static async Task SetupExpectation(MockServerClient mockServerClient, bool secure)
        {
            await mockServerClient.ResetAsync();

            await mockServerClient.When(Request()
                                        .WithSecure(secure)
                                        .WithMethod(HttpMethod.Get)
                                        .WithPath("/hello"),
                                        Times.Unlimited()
                                        ).RespondAsync(Response()
                                                       .WithDelay(TimeSpan.FromSeconds(0))
                                                       .WithStatusCode(200)
                                                       .WithBody("{\"message\": \"hello\"}"));
        }
Example #7
0
        public void ShouldVerifyMultipleRequests()
        {
            MockServerClient
            .When(Request().WithPath("/hello"), Times.Exactly(1))
            .Respond(Response().WithStatusCode(200).WithBody("hello").WithDelay(TimeSpan.FromSeconds(0)));

            MockServerClient
            .When(Request().WithPath("/world"), Times.Exactly(1))
            .Respond(Response().WithStatusCode(200).WithBody("world").WithDelay(TimeSpan.FromSeconds(0)));

            SendRequest(BuildGetRequest("/hello"), out var helloResponse, out _);
            SendRequest(BuildGetRequest("/world"), out var worldResponse, out _);

            Assert.Equal("hello", helloResponse);
            Assert.Equal("world", worldResponse);

            Assert.NotNull(MockServerClient.Verify(Request().WithPath("/hello"), Request().WithPath("/world")));
        }
        private static void SetupMockServerRequest(MockServerClient mockServerClient, Expectation expectation, HttpRequest httpRequest, HttpResponse httpResponse)
        {
            var isSecure       = expectation.HttpRequest.IsSecure.HasValue && expectation.HttpRequest.IsSecure.Value;
            var unlimitedTimes = expectation.Times == null || expectation.Times.IsUnlimited;

            mockServerClient
            .When(httpRequest
                  .WithMethod(expectation.HttpRequest.Method)
                  .WithPath(expectation.HttpRequest.Path)
                  .WithQueryStringParameters(expectation.HttpRequest.Parameters.ToArray())
                  .WithBody(expectation.HttpRequest.Body)
                  .WithSecure(isSecure),
                  unlimitedTimes ? Times.Unlimited() : Times.Exactly(expectation.Times.Count))
            .Respond(httpResponse
                     .WithStatusCode(expectation.HttpResponse.StatusCode)
                     .WithHeaders(expectation.HttpResponse.Headers.ToArray())
                     .WithBody(expectation.HttpResponse.Body ?? string.Empty)
                     .WithDelay(GetTimeSpanDelay(expectation.HttpResponse.Delay)));
        }
        public async Task ShouldMatchHighPriorityFirst()
        {
            await MockServerClient
            .When(Request().WithPath("/hello"), Times.Once(), 5)
            .RespondAsync(Response()
                          .WithStatusCode(200)
                          .WithBody("{\"msg\": \"first\"}")
                          .WithDelay(TimeSpan.Zero));

            await MockServerClient
            .When(Request().WithPath("/hello"), Times.Once(), 10)
            .RespondAsync(Response()
                          .WithStatusCode(200)
                          .WithBody("{\"msg\": \"second\"}")
                          .WithDelay(TimeSpan.Zero));

            var response = await SendRequestAsync(BuildGetRequest("/hello"));

            Assert.Equal("{\"msg\": \"second\"}", await response.Content.ReadAsStringAsync());
        }
Example #10
0
        public void ShouldRetrieveRecordedRequests()
        {
            // arrange
            var request = Request().WithMethod(HttpMethod.Get).WithPath("/hello");

            MockServerClient
            .When(request)
            .Respond(Response().WithBody("hello"));

            // act
            SendRequest(BuildGetRequest("/hello"), out _, out var statusCode1);
            SendRequest(BuildGetRequest("/hello"), out _, out var statusCode2);

            var result = MockServerClient.RetrieveRecordedRequests(request);

            // assert
            Assert.Equal(2, result.Length);
            Assert.Equal(HttpStatusCode.OK, statusCode1);
            Assert.Equal(HttpStatusCode.OK, statusCode2);
            Assert.Equal(3, result[0].Headers.Count);
            Assert.True(result[0].Headers.Exists(h => h.Name == "Host"));
        }
Example #11
0
        private async Task SetupPostExpectation(bool unlimited = true, int times = 0, string reasonPhrase = null)
        {
            const string body = "{\"name\": \"foo\"}";

            await MockServerClient
            .When(Request()
                  .WithMethod("POST")
                  .WithPath("/customers")
                  .WithHeaders(
                      new Header("Content-Type", "application/json; charset=utf-8"),
                      new Header("Content-Length", body.Length.ToString()))
                  .WithHeader("Host", HostHeader)
                  .WithKeepAlive(true)
                  .WithQueryStringParameter("param", "value")
                  .WithBody(body),
                  unlimited?Times.Unlimited() : Times.Exactly(times))
            .RespondAsync(Response()
                          .WithStatusCode(HttpStatusCode.Created)
                          .WithReasonPhrase(reasonPhrase)
                          .WithHeader("Content-Type", "application/json")
                          .WithBody("{ \"id\": \"123\" }"));
        }
Example #12
0
        public void ShouldVerifyExactlyFailed()
        {
            // arrange
            var request = Request().WithMethod(HttpMethod.Get).WithPath("/hello");

            MockServerClient
            .When(request, Times.Unlimited())
            .Respond(Response().WithStatusCode(200).WithBody("hello").WithDelay(TimeSpan.FromSeconds(0)));

            // act
            SendRequest(BuildGetRequest("/hello"), out _, out _);

            // assert
            var ex = Assert.Throws <AssertionException>(() =>
            {
                MockServerClient.Verify(Request()
                                        .WithMethod(HttpMethod.Get)
                                        .WithPath("/hello"), VerificationTimes.Exactly(2));
            });

            Assert.StartsWith("Request not found exactly 2 times", ex.Message);
        }
Example #13
0
        public void ShouldForwardRequestUsingHttpSchemeEnum()
        {
            // arrange
            var request = Request().WithMethod("GET").WithPath("/hello");

            var host = MockServerClient.ServerAddress().Host;
            var port = MockServerClient.ServerAddress().Port;

            MockServerClient
            .When(request, Times.Exactly(1))
            .Forward(Forward()
                     .WithScheme(HttpScheme.Https)
                     .WithHost(host)
                     .WithPort(port));

            // act
            SendRequest(BuildGetRequest("/hello"), out _, out _);

            var result = MockServerClient.RetrieveRecordedRequests(request);

            // assert
            Assert.Equal(2, result.Length);
        }
Example #14
0
        public void ShouldClearExpectation()
        {
            // arrange
            var request = Request().WithMethod(HttpMethod.Get).WithPath("/hello");

            MockServerClient
            .When(request, Times.Unlimited())
            .Respond(Response().WithStatusCode(200).WithBody("hello"));

            // act 1
            SendRequest(BuildGetRequest("/hello"), out var responseBody, out var statusCode);

            // assert
            Assert.Equal(HttpStatusCode.OK, statusCode);
            Assert.Equal("hello", responseBody);

            // act 2
            Assert.NotNull(MockServerClient.Clear(request));

            SendRequest(BuildGetRequest("/hello"), out responseBody, out statusCode);

            // assert
            Assert.Equal(HttpStatusCode.NotFound, statusCode);
        }