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); }
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); }
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); } }
public void ShouldVerifyZeroInteractionsFailed() { SendHello(1); var ex = Assert.Throws <AssertionException>(() => { MockServerClient.VerifyZeroInteractions(); }); Assert.StartsWith("Request not found exactly 0 times", ex.Message); }
public void ShouldVerifyAtMostSuccess() { SendHello(1); Assert.NotNull(MockServerClient.Verify(Request() .WithMethod(HttpMethod.Get) .WithPath("/hello"), VerificationTimes.AtMost(2))); }
public void ShouldVerifyMultipleRequestsFailed() { var ex = Assert.Throws <AssertionException>(() => { MockServerClient.Verify(Request().WithPath("/hello"), Request().WithPath("/world")); }); Assert.StartsWith("Request sequence not found", ex.Message); }
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"))); } }
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); }
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); }
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); }
public void GivenWhenIsCalled_WhenRequestBuilderPassedIsNull_ThenExcptionIsThrown() { using (var httpClient = new HttpClient()) { var mockServerClient = new MockServerClient(httpClient); Assert.Throws <ArgumentNullException>(() => { ExpectationBuilder.When(mockServerClient, null); }); } }
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); } }
private async Task SetupResponseBodyExpectation(BodyContent bodyContent) { await MockServerClient .When(Request() .WithMethod(HttpMethod.Get), Times.Unlimited()) .RespondAsync(Response() .WithStatusCode(200) .WithBody(bodyContent) .WithDelay(TimeSpan.Zero) ); }
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\"}")); }
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); }
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"))); }
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); }
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); } }
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 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); } }
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()); }
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")); }
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\" }")); }
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); }
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); }
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); } }
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); }
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>() ); }