コード例 #1
0
        public async Task Should_Reset_Expecation_On_MockServer()
        {
            // Arrange
            using var client = new MockServerClient("http://localhost:5000");
            var expectation = new ExpectationRequest();

            expectation.Add(new Expectation
            {
                HttpRequest  = HttpRequest.Get("/test"),
                HttpResponse = new HttpResponse(201)
            });

            var response = await client.SetupExpectationAsync(expectation);

            response.EnsureSuccessStatusCode();

            // Act
            var result = await client.Reset();

            // Assert
            var request = new HttpRequestMessage(HttpMethod.Get, new Uri("test", UriKind.Relative));

            response = await client.SendAsync(request);

            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
コード例 #2
0
        public async Task Should_Verify_Expecation_Was_Met_On_MockServer()
        {
            // Arrange
            using var client = new MockServerClient("http://localhost:5000");

            var response = await client.SetupExpectationAsync(new Expectation
            {
                HttpRequest  = HttpRequest.Get("/test"),
                HttpResponse = new HttpResponse(201)
            });

            response.EnsureSuccessStatusCode();

            var request = new HttpRequestMessage(HttpMethod.Get, new Uri("test", UriKind.Relative));

            response = await client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // Act
            var verification = VerificaionRequest.Once(HttpRequest.Get("/test"));

            response = await client.Verify(verification);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.Accepted);
        }
コード例 #3
0
        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);
            }
        }
コード例 #4
0
        public void ShouldVerifyZeroInteractionsFailed()
        {
            SendHello(1);

            var ex = Assert.Throws <AssertionException>(() => { MockServerClient.VerifyZeroInteractions(); });

            Assert.StartsWith("Request not found exactly 0 times", ex.Message);
        }
コード例 #5
0
        public void ShouldVerifyAtMostSuccess()
        {
            SendHello(1);

            Assert.NotNull(MockServerClient.Verify(Request()
                                                   .WithMethod(HttpMethod.Get)
                                                   .WithPath("/hello"), VerificationTimes.AtMost(2)));
        }
コード例 #6
0
        public void ShouldVerifyMultipleRequestsFailed()
        {
            var ex = Assert.Throws <AssertionException>(() =>
            {
                MockServerClient.Verify(Request().WithPath("/hello"), Request().WithPath("/world"));
            });

            Assert.StartsWith("Request sequence not found", ex.Message);
        }
コード例 #7
0
 private async Task <HttpResponseMessage> SendHello(HttpScheme scheme)
 {
     using (var client = new HttpClient(Handler, false))
     {
         var host = MockServerClient.ServerAddress().Host;
         var port = MockServerClient.ServerAddress().Port;
         return(await client.GetAsync(new Uri($"{scheme}://{host}:{port}/hello")));
     }
 }
コード例 #8
0
        public void ShouldVerifyAtLeastFailed()
        {
            var ex = Assert.Throws <AssertionException>(() =>
            {
                MockServerClient.Verify(Request()
                                        .WithMethod(HttpMethod.Get)
                                        .WithPath("/hello"), VerificationTimes.AtLeast(2));
            });

            Assert.StartsWith("Request not found at least 2 times", ex.Message);
        }
コード例 #9
0
        public void ShouldVerifyBetweenFailed()
        {
            var ex = Assert.Throws <AssertionException>(() =>
            {
                MockServerClient.Verify(Request()
                                        .WithMethod(HttpMethod.Get)
                                        .WithPath("/hello"), VerificationTimes.Between(1, 2));
            });

            Assert.StartsWith("Request not found between 1 and 2", ex.Message);
        }
コード例 #10
0
        public void ShouldVerifyOnceFailed()
        {
            var ex = Assert.Throws <AssertionException>(() =>
            {
                MockServerClient.Verify(Request()
                                        .WithMethod(HttpMethod.Get)
                                        .WithPath("/hello"), VerificationTimes.Once());
            });

            Assert.StartsWith("Request not found exactly once", ex.Message);
        }
コード例 #11
0
 public void GivenWhenIsCalled_WhenRequestBuilderPassedIsNull_ThenExcptionIsThrown()
 {
     using (var httpClient = new HttpClient())
     {
         var mockServerClient = new MockServerClient(httpClient);
         Assert.Throws <ArgumentNullException>(() =>
         {
             ExpectationBuilder.When(mockServerClient, null);
         });
     }
 }
コード例 #12
0
        public void GivenWhenIsCalled_WhenParametersAreValid_ThenNewBuilderIsReturnedWithRequestPersisted()
        {
            using (var httpClient = new HttpClient())
            {
                var mockServerClient = new MockServerClient(httpClient);
                var requestBuilder   = RequestBuilder.Request();

                var result = ExpectationBuilder.When(mockServerClient, requestBuilder);

                Assert.Equal(requestBuilder, result.RequestBuilder);
            }
        }
コード例 #13
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)
                   );
 }
コード例 #14
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 _);
            }
        }
コード例 #15
0
 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)
                   );
 }
コード例 #16
0
        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\"}"));
        }
コード例 #17
0
        internal static ExpectationBuilder When(MockServerClient mockServerClient, RequestBuilder requestBuilder)
        {
            if (mockServerClient == null)
            {
                throw new ArgumentNullException(nameof(mockServerClient));
            }
            if (requestBuilder == null)
            {
                throw new ArgumentNullException(nameof(requestBuilder));
            }
            var expectationBuilder = new ExpectationBuilder(mockServerClient, requestBuilder);

            return(expectationBuilder);
        }
コード例 #18
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")));
        }
コード例 #19
0
        public void WhenExpectationsAreLoadedFromFile_ShouldRespondFromTheConfiguredRoutes()
        {
            // arrange
            var filePath = Path.Combine("ExpectationFiles", "TestExpectations.json");

            MockServerClient.LoadExpectationsFromFile(filePath);

            // act
            SendRequest(BuildGetRequest("/entity1?id=1"), out var responseBody1, out _);
            SendRequest(BuildGetRequest("/entity2"), out var responseBody2, out _);
            SendRequest(BuildRequest(HttpMethod.Post, "/entity3", "request3"), out var responseBody3, out _);
            SendRequest(BuildRequest(HttpMethod.Post, "/entity4", "request4"), out var responseBody4, out _);

            // assert
            Assert.Equal("response1", responseBody1);
            Assert.Equal("response2", responseBody2);
            Assert.Equal("response3", responseBody3);
            Assert.Equal("response4", responseBody4);
        }
コード例 #20
0
        public static async Task LoadExpectationsFromFileAsync(this MockServerClient mockServerClient,
                                                               string expectationsFilePath)
        {
            if (!File.Exists(expectationsFilePath))
            {
                throw new FileNotFoundException($"File: {expectationsFilePath} not found!");
            }

            var fileContent  = File.ReadAllText(expectationsFilePath);
            var expectations = JsonConvert.DeserializeObject <IEnumerable <Expectation> >(fileContent);

            foreach (var expectation in expectations)
            {
                var httpRequest  = HttpRequest.Request();
                var httpResponse = HttpResponse.Response();

                await SetupMockServerRequestAsync(mockServerClient, expectation, httpRequest, httpResponse);
            }
        }
コード例 #21
0
        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)));
        }
コード例 #22
0
        public async void GivenExpectationSetOnPath_WhenRequestIsMadeForMatchingPath_ThenMatchIsMade()
        {
            var path = "/pathtest";

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

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

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, path);
                var response           = await httpClient.SendAsync(httpRequestMessage);

                Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
            }
        }
コード例 #23
0
        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());
        }
コード例 #24
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"));
        }
コード例 #25
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\" }"));
        }
コード例 #26
0
        public async Task Should_Build_Expectation()
        {
            // Arrange
            var handler          = new MockHandler(_outputHelper);
            var mockServerClient = new MockServerClient(new HttpClient(handler));

            // Act
            await mockServerClient.SetupAsync(
                builder => builder
                .OnHandling(HttpMethod.Post, request => request.WithPath("some/path").EnableEncryption())
                .RespondWith(HttpStatusCode.Accepted, response => response.WithDelay(10, TimeUnit.Seconds))
                .Setup());

            // Assert
            handler.Expectations.Should().ContainSingle(
                e =>
                e.HttpRequest.Path == "/some/path" &&
                e.HttpRequest.Method == "POST" &&
                e.HttpRequest.Secure == true &&
                e.HttpResponse.Delay.Value == 10 &&
                e.HttpResponse.Delay.TimeUnit == TimeUnit.Seconds);
        }
コード例 #27
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);
        }
コード例 #28
0
        public async void GivenExpectationIsSetOnBody_WhenRequestIsMadeWithNonMatchingBody_ThenRequestIsNotMatched()
        {
            var path        = "/bodytest";
            var requestBody = "This is the request body";

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

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

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, path);
                httpRequestMessage.Content = new StringContent("This body does not match", System.Text.Encoding.UTF8);
                var response = await httpClient.SendAsync(httpRequestMessage);

                Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode);
            }
        }
コード例 #29
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);
        }
コード例 #30
0
        public async void GivenSetExpectationsIsCalled_ThenApiIsCalledToSetExpectations()
        {
            var expectedUri    = "http://mockserverhost:1080/expectation";
            var messageHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            messageHandler
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK
            })
            .Verifiable();

            var httpClient = new HttpClient(messageHandler.Object);

            httpClient.BaseAddress = new Uri("http://mockserverhost:1080/");

            var mockServerClient = new MockServerClient(httpClient);

            await mockServerClient.SetExpectations(new Expectation());

            messageHandler.Protected().Verify(
                "SendAsync",
                Moq.Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Put &&
                                               req.RequestUri.ToString() == expectedUri
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }