コード例 #1
0
        public void WhenRegisteringAnInteractionThatIsNeverSent_ThenPactFailureExceptionIsThrown()
        {
            _mockProviderService
            .UponReceiving("A POST request to create a new thing")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Post,
                Path    = "/things",
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    thingId = 1234,
                    type    = "Awesome"
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status = 201
            });

            Assert.Throws <PactFailureException>(() => _mockProviderService.VerifyInteractions());
        }
コード例 #2
0
        public async Task be_able_to_order_a_beer_when_is_old_enoughAsync()
        {
            mockProviderService
            .Given("A client is adult (age >= 18)")
            .UponReceiving("A POST request to order a beer")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Post,
                Path    = BEERS_PATH,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" },
                },
                Body = new
                {
                    Age = 18
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 201,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = "Created"
            });

            await alcoholic.OrderAsync(ADULT);

            mockProviderService.VerifyInteractions();
        }
コード例 #3
0
        public void TestGetTribbleReturnsATribble()
        {
            _mockProviderService
            .Given("There is a tribble with id '1'")
            .UponReceiving("A GET request to retrieve the tribble")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/tribbles/1",
                Headers = new Dictionary <string, string>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    Id        = 1,
                    Colour    = "blue",
                    Furryness = "High",
                    Hungry    = true
                }
            });
            var consumer = new TribbleClient.Client(_mockProviderServiceBaseUri);
            var result   = consumer.GetTribble(1);

            Assert.AreEqual("blue", result.Colour);
            _mockProviderService.VerifyInteractions();
        }
コード例 #4
0
        public async Task TestGetOnRootOfExampleApiReturnsExpectedThing()
        {
            _mockProviderService.Given("I just hit controller root")
            .UponReceiving("A GET request at the root of the controller")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/"
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "text/plain; charset=utf-8" }
                },
                Body = "Ahh OK"
            });

            var consumer = new ExampleApiClient();

            var result = await consumer.GetString(_mockProviderServiceBaseUri);

            Assert.AreEqual("Ahh OK", result);

            _mockProviderService.VerifyInteractions(); //NOTE: Verifies that interactions registered on the mock provider are called at least once
        }
コード例 #5
0
        public async Task WhenCryptocurrencyIsNotSupportedReturnsNotFound()
        {
            const string cryptocurrency    = "unknownCryptocurrency";
            var          endpointUnderTest = $"/api/priceindex/{cryptocurrency}";

            _mockProviderService
            .UponReceiving($"A GET request to get price indexes for '{cryptocurrency}' cryptocurrency")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = endpointUnderTest
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status = (int)HttpStatusCode.NotFound
            });

            var consumer = new TestWebClient(_mockProviderServiceBaseUri);

            var(statusCode, coinDeskResponse) = await consumer.Get(endpointUnderTest);

            Assert.Equal(HttpStatusCode.NotFound, statusCode);
            Assert.Null(coinDeskResponse);

            _mockProviderService.VerifyInteractions();
        }
コード例 #6
0
        public void GetAllCars_WhenCalled_ReturnsAllEvents()
        {
            var test = new[]
            {
                new
                {
                    carId    = Guid.Parse("45D80D13-D5A2-48D7-8353-CBB4C0EAABF5"),
                    mileage1 = 0,
                    fuel     = "Gasoline"
                },
                new
                {
                    carId    = Guid.Parse("83F9262F-28F1-4703-AB1A-8CFD9E8249C9"),
                    mileage1 = 0,
                    fuel     = "Gasoline"
                },
                new
                {
                    carId    = Guid.Parse("3E83A96B-2A0C-49B1-9959-26DF23F83AEB"),
                    mileage1 = 15000,
                    fuel     = "Diesel"
                }
            };

            var res = new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = test
            };

            //Arrange
            _mockProviderService.Given("there are cars with ids '45D80D13-D5A2-48D7-8353-CBB4C0EAABF5', '83F9262F-28F1-4703-AB1A-8CFD9E8249C9' and '3E83A96B-2A0C-49B1-9959-26DF23F83AEB'")
            .UponReceiving("a request to retrieve all cars")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/cars",
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" },
                }
            })
            .WillRespondWith(res);

            var consumer = new CarsApiClient(_mockProviderServiceBaseUri);

            //Act
            var events = consumer.GetAllCars();

            //Assert
            Assert.NotEmpty(events);
            Assert.Equal(3, events.Count());


            _mockProviderService.VerifyInteractions();
        }
コード例 #7
0
        public void GetAllEvents_WhenCalled_ReturnsAllEvents()
        {
            //Arrange
            _mockProviderService.Given("There are events with ids '45D80D13-D5A2-48D7-8353-CBB4C0EAABF5', '83F9262F-28F1-4703-AB1A-8CFD9E8249C9' and '3E83A96B-2A0C-49B1-9959-26DF23F83AEB'")
            .UponReceiving("A GET request to retrieve all events")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/events",
                Headers = new Dictionary <string, string>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new []
                {
                    new
                    {
                        eventId   = Guid.Parse("45D80D13-D5A2-48D7-8353-CBB4C0EAABF5"),
                        timestamp = "2014-06-30T01:37:41.0660548",
                        eventType = "SearchView"
                    },
                    new
                    {
                        eventId   = Guid.Parse("83F9262F-28F1-4703-AB1A-8CFD9E8249C9"),
                        timestamp = "2014-06-30T01:37:52.2618864",
                        eventType = "DetailsView"
                    },
                    new
                    {
                        eventId   = Guid.Parse("3E83A96B-2A0C-49B1-9959-26DF23F83AEB"),
                        timestamp = "2014-06-30T01:38:00.8518952",
                        eventType = "SearchView"
                    }
                }
            });

            var consumer = new EventsApiClient(_mockProviderServiceBaseUri);

            //Act
            var events = consumer.GetAllEvents();

            //Assert
            Assert.NotEmpty(events);
            Assert.Equal(3, events.Count());


            _mockProviderService.VerifyInteractions();
        }
コード例 #8
0
        public void GetAllEvents_WithNoAuthorizationToken_ShouldFail()
        {
            //Arrange
            _mockProviderService.Given("there are events with ids '45D80D13-D5A2-48D7-8353-CBB4C0EAABF5', '83F9262F-28F1-4703-AB1A-8CFD9E8249C9' and '3E83A96B-2A0C-49B1-9959-26DF23F83AEB'")
            .UponReceiving("a request to retrieve all events with no authorization")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/events",
                Headers = new Dictionary <string, string>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 401,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    message = "Authorization has been denied for this request."
                }
            });

            var consumer = new EventsApiClient(_mockProviderServiceBaseUri);

            //Act //Assert
            Assert.Throws <HttpRequestException>(() => consumer.GetAllEvents());

            _mockProviderService.VerifyInteractions();
        }
コード例 #9
0
ファイル: PactNetConsumerTests.cs プロジェクト: vanmak/PACT
        public void GetUser_WhenPactExists_ReturnsUser()
        {
            // Arrange
            var expectedUser = new User
            {
                Id         = 0,
                Name       = "Tony Stark",
                Occupation = "Iron Man",
                Roles      = new List <Role> {
                    new Role {
                        Name        = "Genius",
                        Description = "Building Jarvis, aka Vision, aka AI"
                    },
                    new Role {
                        Name        = "CEO",
                        Description = "Lying to the board"
                    },
                    new Role {
                        Name        = "Fighter",
                        Description = "Made Thanos bleed"
                    }
                }
            };

            _mockProviderService
            .Given("There is a user for the id")
            .UponReceiving("A properly formatted GET request with the user id")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/api/user/0"
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object> {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = expectedUser
            });
            var consumer = new PactNetClient(_baseUri);
            // Act
            var result = consumer.Get(0).GetAwaiter().GetResult();

            // Assert
            Assert.NotNull(result);
            Assert.Equal(result.Id, expectedUser.Id);
            Assert.Equal(result.Name, expectedUser.Name);
            _mockProviderService.VerifyInteractions();
        }
コード例 #10
0
        public void Return_RegionStock_Status_WHEN_Variant_Is_Found()
        {
            // Arrange
            var variantId   = 4567;
            var regionId    = "US";
            var stockStatus = "InStock";

            _mockProviderService
            .Given($"Variant {variantId} exists in region {regionId} and has status {stockStatus}")
            .UponReceiving($"A GET request to retrieve the RegionStock status for variant {variantId} to region {regionId}")
            .With(BuildRegionStockStatusRequest(regionId, variantId))
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new {
                    variantId,
                    status = "InStock"
                }
            });

            // Act
            var regionStock = _sqsRegionStockApiClient.GetRegionStockStatus(regionId, variantId);

            // Assert
            regionStock.Should().NotBeNull();
            regionStock.Value.Should().Be(RegionStockStatus.InStock);
            _mockProviderService.VerifyInteractions();
        }
コード例 #11
0
        public async Task Given_Valid_Id_Should_Return_Dto()
        {
            _mockProviderService
            .Given("Some value")
            .UponReceiving("A GET Request")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/api/values"
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = Match.Type(new { NumberParam = 888, StringParam = "fake" })
            });
            var httpClient = new HttpClient();
            var response   = await httpClient.GetAsync($"{_serviceUri}/api/values");

            var json = await response.Content.ReadAsStringAsync();

            var someDto = JsonConvert.DeserializeObject <SomeDto>(json);

            Assert.Equal(888, someDto.NumberParam);

            _mockProviderService.VerifyInteractions();
        }
コード例 #12
0
        public void IsAlive_WhenApiIsAlive_ReturnsTrue()
        {
            //Arrange
            Guid fixtureIdSet = new Guid("713be2bd-36e3-43b8-ae2b-0ddeac06cd9f");

            _mockProviderService.Given("a request to check the api response")
            .UponReceiving("I call fixture service using a valid fixture Id")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = $"/api/v1.0/fixture/{fixtureIdSet}",
                Headers = new Dictionary <string, object> {
                    { "Accept", "application/json" },
                    { "X-Clarksons-Security-Cloud", "9xoNm1ZZk6zn3uzu2X18xXtRM5MurptRBsWGA4A1zIM+HSZdJDp9aqlRD+oCsNDOL4UPwU5oFNJHa3T/c1FeVG4EBodw/ybiZq8xb4XSPcELNZ3IKbM1d1tvVGBbWi8q7QfxRODngc+yd25V6fW+Lw==" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status = 200,
            });

            var consumer = new FixtureConsumer(_mockProviderServiceBaseUri);

            //Act
            var result = consumer.GetFixture(fixtureIdSet, "9xoNm1ZZk6zn3uzu2X18xXtRM5MurptRBsWGA4A1zIM+HSZdJDp9aqlRD+oCsNDOL4UPwU5oFNJHa3T/c1FeVG4EBodw/ybiZq8xb4XSPcELNZ3IKbM1d1tvVGBbWi8q7QfxRODngc+yd25V6fW+Lw==");

            //Assert
            //Assert.Equal(fixtureIdSet, result.FixtureId);

            _mockProviderService.VerifyInteractions();
        }
コード例 #13
0
        public async Task Search_WhenApiFindsCustomer_ReturnsTheCustomer()
        {
            // Arrange

            _mockProviderService
            .Given("There is a customer with an ID of 1")
            .UponReceiving("A GET request to retrieve the customer")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/customer/1",
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    id        = 1,
                    firstName = "Paul",
                    surname   = "Davidson"
                }
            });

            var consumer = GetCustomerClient();


            // Act

            var customer = await consumer.GetAsync(1);


            // Assert
            Assert.Equal(1, customer.Id);
            Assert.Equal("Paul", customer.FirstName);
            Assert.Equal("Davidson", customer.Surname);

            _mockProviderService.VerifyInteractions();
        }
コード例 #14
0
        public async Task GetQuizzes_WhenSomeQuizzesExists_ReturnsTheQuizzes()
        {
            _mockProviderService
            .Given("There are some quizzes")
            .UponReceiving("A GET request to retrieve the quizzes")
            .With(new ProviderServiceRequest {
                Method = HttpVerb.Get, Path = "/api/quizzes", Headers = new Dictionary <string, object> {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object> {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new[] { new { id = 123, title = "This is quiz 123" }, new { id = 124, title = "This is quiz 124" } }
            });

            var consumer = new QuizClient(_mockProviderServiceBaseUri, Client);

            var result = await consumer.GetQuizzesAsync(CancellationToken.None);

            Assert.True(string.IsNullOrEmpty(result.ErrorMessage), result.ErrorMessage);
            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Assert.NotEmpty(result.Value);
            Assert.Equal(2, result.Value.Count());

            _mockProviderService.VerifyInteractions();
        }
コード例 #15
0
ファイル: Facts.cs プロジェクト: Zhengquan/PactDemo
        public void failed_test_case_send_request_without_extra_header()
        {
            _mockProviderService
            .Given("There is a something with id 'tester'")
            .UponReceiving("A GET request to retrieve the something")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/somethings/tester",
                Headers = new Dictionary <string, string>
                {
                    { "Accept", "application/json" },
                    { "Origin", "http://localhost.com" },
                    { "Referrer", "http://baidu.com/index.html" },
                    { "Agent", "1111" },
                    { "Service", "Product" },
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    id        = "tester",
                    firstName = "Totally",
                    lastName  = "Awesome"
                }
            });

            using (var client = new HttpClient {
                BaseAddress = new Uri(_mockProviderServiceBaseUri)
            })
            {
                var request = new HttpRequestMessage(HttpMethod.Get, "/somethings/tester");
                request.Headers.Add("Accept", "application/json");

                client.SendAsync(request).Wait();
            }

            _mockProviderService.VerifyInteractions();
        }
コード例 #16
0
        public async void GetRecipes_WillReturn200()
        {
            var response = new List <object>();

            response.Add(
                new
            {
                name   = "My another recipe",
                author = "*****@*****.**",
                userId = "auth0|foobar",
                style  = "IPA"
            }
                );

            _mockProviderService
            .Given("There is some recipes")
            .UponReceiving("GET request to retrieve recipes")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = "/v1/recipe",
                Query  = "userId=auth0userid"
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Body    = response,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json" }
                }
            });

            var consumer = CreateConsumer();

            var result = await consumer.SearchRecipes(new RecipeSearchFilters
            {
                UserId = "auth0userid"
            });

            Assert.Equal(result.Count(), response.Count());
            _mockProviderService.VerifyInteractions();
        }
コード例 #17
0
        public async Task AddWord_Should_Return_First_Letter_And_Modify_State()
        {
            //Arrange
            _mockProviderService.Given("there is a count of 1 for words beginning with 'A'")
            .UponReceiving("a request with the word 'Aardvark'")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Put,
                Path    = "/AddWord/Aardvark",
                Headers = new Dictionary <string, string>
                {
                    { "Content-Length", "0" },
                    { "Content-Type", "text/plain; charset=utf-8" },
                    { "Host", "localhost:1234" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application-json; charset=utf-8" }
                },
                Body = new
                {
                    Letter = "A",
                    Count  = "2"
                }
            });

            var uriResolver = A.Fake <IServiceUriResolver>();

            A.CallTo(() => uriResolver.GetServiceUri()).Returns(new Uri(_mockProviderServiceBaseUri));

            var httpCommunicationClientFactory = A.Fake <ICommunicationClientFactory <HttpCommunicationClient> >();

            A.CallTo(httpCommunicationClientFactory)
            .WithReturnType <Task <HttpCommunicationClient> >()
            .Returns(new HttpCommunicationClient(new HttpClient(), _mockProviderServiceBaseUri));

            var fabricClientQueryManager = A.Fake <IFabricClientQueryManager>();

            var consumer = new DefaultController(uriResolver,
                                                 fabricClientQueryManager,
                                                 httpCommunicationClientFactory
                                                 );

            var result = await consumer.AddWord("Aardvark");

            var content = await((StringContent)result.Content).ReadAsStringAsync();

            Assert.Equal("<h1>Aardvark</h1> added to partition with key <h2>1</h2>", content);

            _mockProviderService.VerifyInteractions();
        }
        public void GetAsync_WhenIdAndCancellationTokenIsPassedIn_ReturnsEntity()
        {
            // arrange
            DateTime?startDate = new DateTime(2014, 10, 22);
            DateTime?endDate   = new DateTime(2014, 10, 29);

            _mockProviderService
            .Given(string.Format("Given I have Timesheet data for the date range {0} to {1}", startDate, endDate))
            .UponReceiving(string.Format("A GET request for Timesheet data for the daternage {0} to {1}", startDate, endDate))
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = string.Format("/accountright/{0}/{1}/{2}",
                                       _cfUid,
                                       _service.Route,
                                       _uid),
                Headers = new Dictionary <string, string>
                {
                    { "Authorization", "Bearer" },
                    { "Accept-Encoding", "gzip" },
                    { "User-Agent", ApiRequestHelper.UserAgent },
                    { "x-myobapi-key", "" },
                    { "x-myobapi-version", "v2" },
                    { "x-myobapi-cftoken", Convert.ToBase64String(Encoding.UTF8.GetBytes("Administrator:")) },
                },
                Query = string.Format("StartDate={0}&EndDate={1}",
                                      startDate.Value.Date.ToString("s"),
                                      endDate.Value.Date.ToString("s"))
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body =
                    new         //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined
                {
                    StartDate = startDate.Value.Date.ToString("s"),
                    EndDate   = endDate.Value.Date.ToString("s")
                }
            });


            // act
            var result = _service.GetAsync(_cf, _uid, startDate.Value, endDate.Value, new CompanyFileCredentials("Administrator", ""), new CancellationToken()).Result;

            // assert
            Assert.NotNull(result);

            _mockProviderService.VerifyInteractions();
        }
コード例 #19
0
        public void GetSomething_WhenTheTesterSomethingExists_ReturnsTheSomething()
        {
            //Arrange
            _mockProviderService
            .Given("There is a something with id 'tester'")
            .UponReceiving("A POST request to retrieve the something")
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Post,
                Path   = "/posts",

                Headers = new Dictionary <string, object>
                {
                    {
                        "Content-Type", "application/json"
                    },

                    {
                        "Accept", "application/json"
                    }
                },

                Body = new   //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined
                {
                    UserId = "123",
                    Body   = "postBody",
                    Id     = "1234",
                    Title  = "postTitle"
                }
            }
                  )
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 201,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                }
            });   //NOTE: WillRespondWith call must come last as it will register the interaction

            //_mockProviderService.VerifyInteractions(); //NOTE: Verifies that interactions registered on the mock provider are called once and only once

            var consumer = new ApiClient(_mockProviderServiceBaseUri);

            //Act
            var result = consumer.GetResponse("Created");

            //Assert
            Assert.AreEqual("Created", result.ToString());

            _mockProviderService.VerifyInteractions(); //NOTE: Verifies that interactions registered on the mock provider are called once and only once
        }
コード例 #20
0
ファイル: ApiClientTests.cs プロジェクト: naavis/pact-example
        public void GetWeather_CityExists_ReturnsWeather()
        {
            _mockService
            .Given("Helsinki is a valid city")
            .UponReceiving("A GET request to retrieve weather for Helsinki")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/weather/Helsinki",
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    temperature = -15.0,
                    humidity    = 80.0,
                    windSpeed   = 5.0
                }
            });

            var api = new ApiClient(_mockServiceUri);

            var result = api.GetWeather("Helsinki").Result;

            Assert.AreEqual(-15.0, result.Temperature);
            Assert.AreEqual(80.0, result.Humidity);
            Assert.AreEqual(5.0, result.WindSpeed);

            _mockService.VerifyInteractions();
        }
コード例 #21
0
        public void Able_To_Retrieve_Consumers()
        {
            mockProviderService        = consumerPact.MockProviderService;
            mockProviderServiceBaseUri = consumerPact.MockProviderServiceBaseUri;
            consumerPact.MockProviderService.ClearInteractions();

            mockProviderService
            .Given("Get customers'")
            .UponReceiving("A GET request to retrieve the customers")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/customers",
                Headers = new Dictionary <string, object>()
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status = 200,
                Body   =
                    new GetCustomersResponse
                {
                    _Embedded = new Embedded
                    {
                        Customer = new Customer[]
                        {
                            new Customer
                            {
                                FirstName = "Tester",
                                LastName  = "Toster"
                            }
                        }
                    }
                },
                Headers = new Dictionary <string, object>()
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                }
            });

            var consumer = new WebShopApiClient(new Uri(mockProviderServiceBaseUri), "user", "password");
            var result   = consumer.GetCustomers().Result;

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(GetCustomersResponse));

            mockProviderService.VerifyInteractions();
            consumerPact.Dispose();
        }
コード例 #22
0
        public async Task GetSomething_TheTesterSomethingExists_ReturnsTheSomething()
        {
            // arrange
            const string expectedId        = "83F9262F-28F1-4703-AB1A-8CFD9E8249C9";
            const string expectedFirstName = "some-first-name-03";
            const string expectedLastName  = "some-last-name";
            const int    expectedAge       = 42;

            var expectedSomething = new Something(expectedId, expectedFirstName, expectedLastName, expectedAge);

            const string guidRegex = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";

            _mockProviderService
            .Given("Some application state")
            .UponReceiving("A GET request to retrieve something")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = Match.Regex($"/somethings/{expectedId}", $"^\\/somethings\\/{guidRegex}$"),
                Query   = "field1=value1&field2=value2",
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = Match.Type(new
                {
                    id        = "83F9262F-28F1-4703-AB1A-8CFD9E8249C9",
                    firstName = "some-first-name-03",
                    lastName  = "some-last-name",
                    age       = 42
                })
            });

            var consumer = new SomethingApiClient($"http://localhost:{MockServerPort}");

            // act
            Something actualSomething = await consumer.GetSomething(expectedId).ConfigureAwait(false);

            // assert
            _mockProviderService.VerifyInteractions();
            actualSomething.Should().BeEquivalentTo(expectedSomething);
        }
        public void WhenApiIsUp_ReturnsTrue()
        {
            //Arrange
            _mockProviderService.UponReceiving("a request to check the api status")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Headers = new Dictionary <string, object> {
                    { "Accept", "application/json" }
                },
                Path = "/echo/status"
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object> {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    up      = true,
                    upSince = DateTime.UtcNow,
                    version = "2.0.0",
                    message = "I'm up and running from last 19 hours."
                }
            });

            var consumer = new ProductApiClient(_serviceBaseUri);

            //Act
            var result = consumer.ApiStatus().Up;

            //Assert
            Assert.True(result);

            _mockProviderService.VerifyInteractions();
        }
コード例 #24
0
        static void Main(string[] args)
        {
            var consumerPact = new ConsumerMyApiPact();

            _mockProviderService        = consumerPact.MockProviderService;
            _mockProviderServiceBaseUri = consumerPact.MockProviderServiceBaseUri;
            consumerPact.MockProviderService.ClearInteractions();
            //NOTE: Clears any previously registered interactions before the test is run


            _mockProviderService
            .Given("Get user with id '1'")
            .UponReceiving("A GET request to retrieve the user")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = "/user/1",
                Headers = new Dictionary <string, string>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new     //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined
                {
                    id        = 1,
                    firstName = "Tanmoy",
                    lastName  = "Saha"
                }
            });     //NOTE: WillRespondWith call must come last as it will register the interaction

            var consumer = new UserApiClient(_mockProviderServiceBaseUri);

            //Act
            var result = consumer.GetUsers(1);

            //Assert
            result.Should().NotBeNull();
            _mockProviderService.VerifyInteractions();
            //NOTE: Verifies that interactions registered on the mock provider are called once and only once

            consumerPact.Dispose();
        }
コード例 #25
0
        public void GetCustomerById_WithNoAuthorizationToken_ShouldFail()
        {
            int customerId = 20;

            //Arrange
            _mockProviderService.Given(String.Format("there is a customer with id '{0}'", customerId))
            .UponReceiving(String.Format("a request to retrieve customer with id '{0}' with no authorization", customerId))
            .With(new ProviderServiceRequest
            {
                Method = HttpVerb.Get,
                Path   = String.Format("/template/api/v1/customer/{0}", customerId)
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status = 401
            });

            var consumer = new CustomerController(_mockProviderServiceBaseUri);

            //Act //Assert
            Assert.ThrowsAny <Exception>(() => consumer.GetCustomerById(customerId));

            _mockProviderService.VerifyInteractions();
        }
コード例 #26
0
        public void Add_customer()
        {
            //Arrange
            _mockProviderService
            .Given("There is a service")
            .UponReceiving("A POST request to create a customer")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Post,
                Path    = "/customers",
                Query   = "",
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new Customer
                {
                    Firstname = "richard",
                    Surname   = "parkins"
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 201,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" },
                    { "Location", "http://localhost:5000/customers/richard-parkins" }
                },
                Body = new Customer
                {
                    Id        = "richard-parkins",
                    Firstname = "richard",
                    Surname   = "parkins"
                }
            });

            var consumer = new PactConsumer(_mockProviderServiceBaseUri);

            //Act
            var result = consumer.CreateUser("richard", "parkins").Result;

            //Assert
            Assert.EndsWith("/customers/richard-parkins", result.ToString());

            _mockProviderService.VerifyInteractions();
        }
コード例 #27
0
        public async Task GetSomething_WhenTheTesterSomethingExists_ReturnsTheSomething()
        {
            string expectedId = "tester";

            // Arrange
            _mockProviderService
            .Given("There is a something with id 'tester'")
            .UponReceiving("A Get request to retrieve the Id of something")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = $"/Somethings/{expectedId}",
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "applciation/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    Id        = "tester",
                    FirstName = "Totally",
                    LastName  = "Awesome"
                }
            });
            var consumer = new SomethingApiClient(_serviceUri);
            // var httpClient = new HttpClient();
            // var response = await httpClient.GetAsync($"{_serviceUri}/somethings/tester");
            // var json = await response.Content.ReadAsStringAsync();
            // var something = JsonConvert.DeserializeObject<Something>(json);

            // Act
            var result = await consumer.GetSomething("tester");

            // Assert
            Assert.Equal(expectedId, result.Id);
            Assert.Equal("Totally", result.FirstName);
            Assert.Equal("Awesome", result.LastName);

            _mockProviderService.VerifyInteractions();
        }
コード例 #28
0
        public async Task Test1()
        {
            _mockProviderService
            .UponReceiving("Receber a previsão do tempo para amanhã")
            .With(new ProviderServiceRequest
            {
                Path    = "/WeatherForecast/tomorrow",
                Method  = HttpVerb.Get,
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" }
                },
                Body = new
                {
                    date         = DateTime.Today.AddDays(1),
                    summary      = "Chilly",
                    temperatureC = 15,
                    temperatureF = 58
                }
            });

            var consumer = new WeatherForecastApiClient(_mockProviderServiceBaseUri);

            // Act
            var result = await consumer.GetForecastTomorrow();

            // Assert
            result.Should().BeEquivalentTo(
                new WeatherForecastResponse
            {
                Date         = DateTime.Today.AddDays(1),
                Summary      = "Chilly",
                TemperatureC = 15,
                TemperatureF = 58
            }
                );

            _mockProviderService.VerifyInteractions();
        }
コード例 #29
0
        public void GetSomething_WhenTheTesterSomethingExists_ReturnsTheSomething()
        {
            //Arrange
            _mockProviderService
            .Given("There is a something with id 'tester'")
            .UponReceiving("A GET request to retrieve the something")
            .With(GetTesterSomethingRequest())
            .WillRespondWith(GetTesterSomethingResponse());

            var consumer = new SomethingApiClient(_mockProviderServiceBaseUri);

            //Act
            var result = consumer.GetSomething("tester");

            //Assert
            Assert.Equal("tester", result.id);
            _mockProviderService.VerifyInteractions();
        }
コード例 #30
0
        public void GetUserById_WhenTheUserExists_ReturnsUser()
        {
            //Arrange
            var guidRegex = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
            var userId    = Guid.Parse("83F9262F-28F1-4703-AB1A-8CFD9E8249C9");

            _mockProviderService
            .Given($"There is an user with id {userId}")
            .UponReceiving($"a request to retrieve user id {userId}")
            .With(new ProviderServiceRequest
            {
                Method  = HttpVerb.Get,
                Path    = Match.Regex($"/api/users/{userId}", $"^\\/api\\/users\\/{guidRegex}$"),
                Headers = new Dictionary <string, object>
                {
                    { "Accept", "application/json" }
                }
            })
            .WillRespondWith(new ProviderServiceResponse
            {
                Status  = 200,
                Headers = new Dictionary <string, object>
                {
                    { "Content-Type", "application/json; charset=utf-8" },
                    { "Server", Match.Type("RubyServer") }
                },
                Body = new
                {
                    userid    = userId,
                    firstName = "Jean",
                    lastName  = "du Jardin"
                }
            });

            var consumer = new UserApiClient(_mockProviderServiceBaseUri);

            //Act
            var result = consumer.GetUserById(userId);

            //Assert
            Assert.Equal(userId, result.UserId);
            Assert.Equal("Jean", result.FirstName);
            _mockProviderService.VerifyInteractions();
        }