Example #1
0
            public void When_verifying_at_or_below_call_count_should_be_true(int callCount, int verifyCount, bool expected)
            {
                IsSent atMost = IsSent.AtMost(callCount);

                // Assert
                atMost.Verify(verifyCount).Should().Be(expected);
            }
Example #2
0
            public void Given_call_count_below_0_when_creating_should_throw(int callCount)
            {
                Action act = () => IsSent.AtMost(callCount);

                // Assert
                act.Should().Throw <ArgumentOutOfRangeException>().WithParamName(nameof(callCount));
            }
Example #3
0
            public void Given_call_count_at_or_above_0_when_creating_should_not_throw(int callCount)
            {
                Action act = () => IsSent.AtMost(callCount);

                // Assert
                act.Should().NotThrow <ArgumentOutOfRangeException>();
            }
Example #4
0
            public void When_verifying_anything_other_than_1_should_be_false(int verifyCount, bool expected)
            {
                IsSent once = IsSent.Once();

                // Assert
                once.Verify(verifyCount).Should().Be(expected);
            }
Example #5
0
            public void When_verifying_at_or_above_call_count_should_be_true(int verifyCount, bool expected)
            {
                IsSent atLeastOnce = IsSent.AtLeastOnce();

                // Assert
                atLeastOnce.Verify(verifyCount).Should().Be(expected);
            }
Example #6
0
            public void When_verifying_above_or_below_call_count_should_be_false(int callCount, int verifyCount, bool expected)
            {
                IsSent exactly = IsSent.Exactly(callCount);

                // Assert
                exactly.Verify(verifyCount).Should().Be(expected);
            }
Example #7
0
            public void When_verifying_more_than_0_should_be_false(int verifyCount, bool expected)
            {
                IsSent never = IsSent.Never();

                // Assert
                never.Verify(verifyCount).Should().Be(expected);
            }
Example #8
0
        public async Task Given_request_is_configured_to_have_different_responses_should_return_response_in_sequence()
        {
            _sut.When(_ => { })
            .Respond(HttpStatusCode.BadRequest)
            .Respond(HttpStatusCode.BadGateway)
            .Respond(HttpStatusCode.OK)
            .Verifiable();

            // Act
            HttpResponseMessage response1 = await _httpClient.GetAsync("");

            HttpResponseMessage response2 = await _httpClient.GetAsync("");

            HttpResponseMessage response3 = await _httpClient.GetAsync("");

            HttpResponseMessage response4 = await _httpClient.GetAsync("");

            // Assert
            response1.Should().HaveStatusCode(HttpStatusCode.BadRequest);
            response2.Should().HaveStatusCode(HttpStatusCode.BadGateway);
            response3.Should().HaveStatusCode(HttpStatusCode.OK);
            response4.Should().HaveStatusCode(HttpStatusCode.OK);
            _sut.Verify(matching => matching.Method("GET"), IsSent.Exactly(4));
            _sut.VerifyNoOtherRequests();
        }
Example #9
0
        public async Task Given_request_is_not_verified_when_verifying_no_other_calls_should_throw()
        {
            _sut.When(matching => matching.Method("GET"))
            .Respond(HttpStatusCode.OK)
            .Verifiable();

            await _httpClient.GetAsync("");

            await _httpClient.PutAsync("", new StringContent("data"));

            await _httpClient.PostAsync("", new StringContent("data"));

            await _httpClient.GetAsync("");

            await _httpClient.PutAsync("", new StringContent("data"));

            // Verify GET and PUT via different means, but not POST
            _sut.Verify(matching => matching.Method("PUT"), IsSent.Exactly(2));
            _sut.Verify();

            // Act
            Action act = () => _sut.VerifyNoOtherRequests();

            // Assert
            act.Should()
            .Throw <HttpMockException>("the POST request was not verified")
            .WithMessage("There are 1 unverified requests*Method: POST,*");
        }
Example #10
0
        public async Task Given_httpContent_response_when_sending_requests_it_should_not_throw_for_second_request_and_return_same_content()
        {
            const string data = "data";

            using HttpContent httpContent = new StringContent(data);
            _sut.When(matching => { })
            .Respond(HttpStatusCode.OK, httpContent)
            .Verifiable();

            // Act
            HttpResponseMessage firstResponse = await _httpClient.GetAsync("url");

            HttpResponseMessage secondResponse     = null;
            Func <Task <HttpResponseMessage> > act = async() => secondResponse = await _httpClient.GetAsync("url");

            // Assert
            act.Should().NotThrow();

            _sut.Verify(matching => { }, IsSent.Exactly(2));
            firstResponse.Content.Should().BeOfType <ByteArrayContent>("a buffered copy is created and returned for all responses");
            firstResponse.Content.Should().NotBeSameAs(secondResponse.Content);
            await(await firstResponse.Should()
                  .HaveContentAsync(await secondResponse.Content.ReadAsStringAsync()))
            .And.HaveContentAsync(data);

            _sut.VerifyNoOtherRequests();
        }
Example #11
0
        public async Task Given_stream_response_when_sending_requests_it_should_buffer_response(bool isSeekableStream)
        {
            const string data = "data";

            byte[] buffer = Encoding.UTF8.GetBytes(data);
            using Stream stream = new CanSeekMemoryStream(buffer, isSeekableStream);
            _sut.When(matching => { })
            .Respond(HttpStatusCode.OK, stream, "text/plain")
            .Verifiable();

            // Act
            HttpResponseMessage firstResponse = await _httpClient.GetAsync("url");

            HttpResponseMessage secondResponse     = null;
            Func <Task <HttpResponseMessage> > act = async() => secondResponse = await _httpClient.GetAsync("url");

            // Assert
            act.Should().NotThrow();

            _sut.Verify(matching => { }, IsSent.Exactly(2));
            firstResponse.Content.Should().NotBeSameAs(secondResponse.Content);
            await(await firstResponse.Should()
                  .HaveContentAsync(await secondResponse.Content.ReadAsStringAsync()))
            .And.HaveContentAsync(data);

            _sut.VerifyNoOtherRequests();
        }
Example #12
0
        /// <summary>
        /// Verifies that a request matching the specified match conditions has been sent.
        /// </summary>
        /// <param name="matching">The conditions to match.</param>
        /// <param name="times">The number of times a request is allowed to be sent.</param>
        /// <param name="because">The reasoning for this expectation.</param>
        public async Task VerifyAsync(Action <RequestMatching> matching, IsSent times, string because = null)
        {
            if (matching is null)
            {
                throw new ArgumentNullException(nameof(matching));
            }

            if (times is null)
            {
                times = IsSent.AtLeastOnce();
            }

            var rm = new RequestMatching();

            matching(rm);

            IReadOnlyCollection <IAsyncHttpRequestMatcher> matchers        = rm.Build();
            IReadOnlyList <IInvokedHttpRequest>            matchedRequests = InvokedRequests;

            if (matchers.Count > 0)
            {
                var list = new List <IInvokedHttpRequest>();
                foreach (IInvokedHttpRequest invokedHttpRequest in InvokedRequests)
                {
                    var requestContext = new MockHttpRequestContext(invokedHttpRequest.Request);
                    if (await matchers.AllAsync(requestContext).ConfigureAwait(false))
                    {
                        list.Add(invokedHttpRequest);
                    }
                }

                matchedRequests = list;
            }

            if (!times.Verify(matchedRequests.Count))
            {
                throw new HttpMockException(times.GetErrorMessage(matchedRequests.Count, BecauseMessage(because)));
            }

            foreach (InvokedHttpRequest r in matchedRequests.Cast <InvokedHttpRequest>())
            {
                r.MarkAsVerified();
            }
        }
Example #13
0
        public void Given_request_is_configured_to_fail_and_then_succeed_should_return_response_in_sequence()
        {
            var ex = new Exception("My exception");

            _sut.When(_ => { })
            .Throws(ex)
            .TimesOutAfter(500)
            .Respond(HttpStatusCode.OK);

            // Act & assert
            Func <Task <HttpResponseMessage> > act1 = () => _httpClient.GetAsync("");
            Func <Task <HttpResponseMessage> > act2 = () => _httpClient.GetAsync("");
            HttpResponseMessage response3           = null;
            Func <Task <HttpResponseMessage> > act3 = async() => response3 = await _httpClient.GetAsync("");

            // Assert
            act1.Should().Throw <Exception>().Which.Should().Be(ex);
            act2.Should().Throw <TaskCanceledException>();
            act3.Should().NotThrow();
            response3.Should().HaveStatusCode(HttpStatusCode.OK);

            _sut.Verify(matching => matching.Method("GET"), IsSent.Exactly(3));
            _sut.VerifyNoOtherRequests();
        }
Example #14
0
 /// <summary>
 /// Verifies that a request matching the specified match conditions has been sent.
 /// </summary>
 /// <param name="matching">The conditions to match.</param>
 /// <param name="times">The number of times a request is allowed to be sent.</param>
 /// <param name="because">The reasoning for this expectation.</param>
 /// <remarks>
 /// When verifying <see cref="HttpContent"/> using a <see cref="ContentMatcher"/> use the <see cref="VerifyAsync(System.Action{MockHttp.RequestMatching},System.Func{MockHttp.IsSent},string)"/> overload to prevent potential deadlocks.
 /// </remarks>
 public void Verify(Action <RequestMatching> matching, IsSent times, string because = null)
 {
     TaskHelpers.RunSync(() => VerifyAsync(matching, times, because), TimeSpan.FromSeconds(30));
 }
Example #15
0
        public async Task Given_a_request_expectation_when_sending_requests_it_should_correctly_match_and_verify_the_response()
        {
            var postObject = new
            {
                Field1 = true,
                Field2 = "some text",
                Field3 = DateTime.UtcNow
            };
            string jsonPostContent = JsonConvert.SerializeObject(postObject);
            var    lastModified    = new DateTime(2018, 4, 12, 7, 22, 43, DateTimeKind.Local);
            var    postContent     = new StringContent(jsonPostContent, Encoding.UTF8, "application/json")
            {
                Headers =
                {
                    LastModified = lastModified
                }
            };

            // ReSharper disable once JoinDeclarationAndInitializer
            Version version;

#if NETCOREAPP3_1 || NET5_0
            version = _httpClient.DefaultRequestVersion;
#else
#if NETCOREAPP2_1
            version = new Version(2, 0);
#else
            version = new Version(1, 1);
#endif
#endif

            _sut
            .When(matching => matching
                  .RequestUri("http://0.0.0.1/*/action*")
                  .QueryString("test", "$%^&*")
                  .QueryString("test2=value")
                  .Method("POST")
                  .Content(jsonPostContent)
                  .PartialContent(jsonPostContent.Substring(10))
                  .ContentType("application/json; charset=utf-8")
                  .BearerToken()
                  .Header("Content-Length", jsonPostContent.Length)
                  .Header("Last-Modified", lastModified)
                  .Version(version)
                  .Any(any => any
                       .RequestUri("not-matching")
                       .RequestUri("**controller**")
                       )
                  .Where(r => 0 < r.Version.Major)
                  )
            .Callback(() =>
            {
            })
            .Respond(HttpStatusCode.Accepted, JsonConvert.SerializeObject(new
            {
                firstName = "John",
                lastName  = "Doe"
            }))
            .Verifiable();

            // Act
            await _httpClient.GetAsync("http://0.0.0.1/controller/action?test=1");

            var req = new HttpRequestMessage(HttpMethod.Post, "http://0.0.0.1/controller/action?test=%24%25^%26*&test2=value")
            {
                Headers =
                {
                    Authorization = new AuthenticationHeaderValue("Bearer", "some-token")
                },
                Content = postContent,
                Version = version
            };
            HttpResponseMessage response = await _httpClient.SendAsync(req);

            // Assert
            _sut.Verify(matching => matching.RequestUri("**/controller/**"), IsSent.Exactly(2), "we sent it");
#if !NETCOREAPP1_1 // .NET Standard 1.1 disposes content, so can't verify after sending on HttpContent.
            await _sut.VerifyAsync(matching => matching.Content(jsonPostContent), IsSent.Once, "we sent it");
#endif
            _sut.Verify();
            _sut.VerifyNoOtherRequests();

            await response.Should()
            .HaveStatusCode(HttpStatusCode.Accepted)
            .And.HaveContentAsync(JsonConvert.SerializeObject(
                                      new
            {
                firstName = "John",
                lastName  = "Doe"
            })
                                  );
        }
Example #16
0
        public async Task Given_number_of_requests_does_not_match_expected_callCount_when_verifying_should_throw(int requestCount, IsSent isSent)
        {
            for (int i = 0; i < requestCount; i++)
            {
                await _httpClient.GetAsync("url");
            }

            // Act
            Action verifyGet = () => _sut.Verify(
                matching => matching.RequestUri("**/url"),
                isSent
                );

            // Assert
            verifyGet.Should()
            .Throw <HttpMockException>()
            .WithMessage("Expected request to have*");
        }