Example #1
0
            public void Given_call_count_above_or_equal_to_0_when_creating_should_not_throw(int callCount)
            {
                Action act = () => IsSent.Exactly(callCount);

                // Assert
                act.Should().NotThrow <ArgumentOutOfRangeException>();
            }
Example #2
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 #3
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 #4
0
            public void Given_call_count_below_0_when_creating_should_throw(int callCount)
            {
                Action act = () => IsSent.Exactly(callCount);

                // Assert
                act.Should().Throw <ArgumentOutOfRangeException>().WithParamName(nameof(callCount));
            }
Example #5
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 #6
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 #7
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 #8
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 #9
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"
            })
                                  );
        }