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(); }
public void GivenAFilmThatDoesExistWhenGettingTheDescriptionThenTheDescriptionIsReturned(string url) { _fakeOmdbService.Given("The film Inception").UponReceiving("A request for it") .With(OmdbRequest("inception", "2010")).WillRespondWith(OmdbResponse(_inceptionPlot)); var repository = new FilmDescriptionRepository(url); var result = repository.GetDescriptionResult("inception", "2010"); Assert.That(result.Result, Is.EqualTo(RepositoryResult.Successful)); Assert.That(result.Value, Is.EqualTo(_inceptionPlot)); }
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(); }
public void ItHandlesInvalidInstrumentName() { // Arange const string instrument = "Ta"; var invalidRequestMessage = $"{instrument} is not valid"; //Mocking ProviderService //1-Provider State //2-Description for Specified Provider State //3-Specifing the Request //4-The Desired Response for Specified Request _mockProviderService .Given("There is no Instrument") .UponReceiving("An invalid GET request for Instruments with invalid name") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/Instrument", Query = $"name={instrument}" }) .WillRespondWith(new ProviderServiceResponse { Status = 404, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = new { message = invalidRequestMessage, result = "Failed", data = "" } }); // Act var result = HttpUtility.GetInstrumentDesc(instrument, _baseUri) .GetAwaiter() .GetResult(); var resultBodyText = result.Content.ReadAsStringAsync() .GetAwaiter() .GetResult(); // Assert Assert.Contains(invalidRequestMessage, resultBodyText); //Very simple assertion to assert if response message contains expected result. }
public void ItHandlesInvalidDateParam() { // Arange string personMessagebody = "{\"firstName\":\"Alireza\",\"lastName\":\"Oroumand\",\"id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\"}"; _mockProviderService.Given("There is data") .UponReceiving("Valid person Data") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/person/", Query = "id=3fa85f64-5717-4562-b3fc-2c963f66afa6" }) .WillRespondWith(new ProviderServiceResponse { Status = 200, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = personMessagebody }); // Act var result = APICaller.Call(_mockProviderServiceBaseUri, "3fa85f64-5717-4562-b3fc-2c963f66afa6").GetAwaiter().GetResult(); var resultBodyText = result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // Assert Assert.Equal(resultBodyText, personMessagebody); }
public void ItHandlesInvalidDateParam() { // Arange var invalidRequestMessage = "validDateTime is not a date or time"; _mockProviderService.Given("There is data") .UponReceiving("A invalid GET request for Date Validation with invalid date parameter") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/provider", Query = "validDateTime=lolz" }) .WillRespondWith(new ProviderServiceResponse { Status = 400, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = new { message = invalidRequestMessage } }); // Act var result = ConsumerApiClient.ValidateDateTimeUsingProviderApi("lolz", _mockProviderServiceBaseUri).GetAwaiter().GetResult(); var resultBodyText = result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // Assert Assert.Contains(invalidRequestMessage, resultBodyText); }
public static void CreateOn(IMockProviderService customerApi) { customerApi .Given("There is a customer with ID tester") .UponReceiving("A GET request to retrieve the customer") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/customers/tester", Headers = new Dictionary<string, string> { {"Accept", "application/json"}, {"Another", "header"} } }) .WillRespondWith(new ProviderServiceResponse { Status = (int)HttpStatusCode.OK, Headers = new Dictionary<string, string> { {"Content-Type", "application/json; charset=utf-8" }, {"Another", "header"} }, Body = new //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined { Id = "tester", FirstName = "Totally", LastName = "Awesome" } }); //NOTE: WillRespondWith call must come last as it will register the interaction }
public static void CreateOn(IMockProviderService customerApi) { customerApi .Given("Version is 1.2.3.4") .UponReceiving("A GET request to retrieve the version") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/version", Headers = new Dictionary <string, string> { { "Accept", "application/json" }, { "Another", "header" } } }) .WillRespondWith(new ProviderServiceResponse { Status = (int)HttpStatusCode.OK, Headers = new Dictionary <string, string> { { "Content-Type", "application/json; charset=utf-8" }, { "Another", "header" } }, Body = new { Build = "1.2.3.4", Date = "2015-09-17T20:29:13" } }); }
public static void CreateOn(IMockProviderService customerApi) { customerApi .Given("Version is 1.2.3.4") .UponReceiving("A GET request to retrieve the version") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path="/api/version", Headers=new Dictionary<string, string> { {"Accept", "application/json"}, {"Another", "header" } } }) .WillRespondWith(new ProviderServiceResponse { Status = (int)HttpStatusCode.OK, Headers = new Dictionary<string, string> { {"Content-Type", "application/json; charset=utf-8" }, {"Another", "header"} }, Body = new { Build="1.2.3.4", Date="2015-09-17T20:29:13" } }); }
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(); }
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(); }
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(); }
public async Task Consumer() { var article = new { text = "Test pact" }; _mockProviderService .Given("New article") .UponReceiving("Valid POST Article object") .With(new ProviderServiceRequest { Method = HttpVerb.Post, Path = _path, Body = article, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, }) .WillRespondWith(new ProviderServiceResponse { Status = (int)HttpStatusCode.Created, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = new { id = Match.Type(1), creationDate = Match.Type(DateTime.Now), article.text } }); var result = await _consumerPactClassFixture.PostAsync(_path, article); Assert.Equal(HttpStatusCode.Created, result.StatusCode); JsonSerializer.Deserialize <Article>(await result.Content.ReadAsStringAsync()); }
public async Task Consumer() { var firstArticle = DataSeed.GetFirstArticle(); _mockProviderService .Given("Existing article id") .UponReceiving("Valid GET Article") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = _path, }) .WillRespondWith(new ProviderServiceResponse { Status = (int)HttpStatusCode.OK, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = firstArticle }); var result = await _consumerPactClassFixture.GetAsync(_path); Assert.Equal(HttpStatusCode.OK, result.StatusCode); JsonSerializer.Deserialize <Article>(await result.Content.ReadAsStringAsync()); }
public static void CreateOn(IMockProviderService customerApi) { customerApi .Given("There is a customer with ID tester") .UponReceiving("A GET request to retrieve the customer") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/customers/tester", Headers = new Dictionary <string, string> { { "Accept", "application/json" }, { "Another", "header" } } }) .WillRespondWith(new ProviderServiceResponse { Status = (int)HttpStatusCode.OK, Headers = new Dictionary <string, string> { { "Content-Type", "application/json; charset=utf-8" }, { "Another", "header" } }, Body = new //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined { Id = "tester", FirstName = "Totally", LastName = "Awesome" } }); //NOTE: WillRespondWith call must come last as it will register the interaction }
public async void RetrieveProducts() { // Arrange _mockProviderService.Given("products exist") .UponReceiving("A request to get products") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/products", }) .WillRespondWith(new ProviderServiceResponse { Status = 200, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = new MinTypeMatcher(new { id = "27", name = "burger", type = "food" }, 1) }); // Act var consumer = new ProductClient(); List <Product> result = await consumer.GetProducts(_mockProviderServiceBaseUri); // Assert result.Should().NotBeNull(); result.Should().HaveCount(1); result[0].id.Should().Equals("27"); result[0].name.Should().Equals("burger"); result[0].type.Should().Equals("food"); }
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(); }
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(); }
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(); }
public override Task <IRestResponse> ExecuteTaskAsync(IRestRequest request) { _mockProviderService .Given(ConditionDescription) .UponReceiving(RequestDescription) .With(request) .WillRespondWith(Response); return(base.ExecuteTaskAsync(request)); }
public void ItHandlesInvalidDateParam() { /* * All test cases follow the same 3 steps * 1) Mock out an interaction withe provider api * 2) Interaction with the mocked out interaction using the Consumer [HttpDelete] * 3) Aseert the result is what we expected * * * public IActionResult Delete(inputType id) * { * //TODO: Implement Realistic Implementation * return Ok(); * } */ var invalidRequestMessage = "validDateTime is not a date or time"; _mockProviderService.Given("There is data") .UponReceiving("A invalid Get request for Date Validation with invalid data") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/provider", Query = "validDateTime=lolz" }) .WillRespondWith(new ProviderServiceResponse { Status = 400, Headers = new Dictionary <string, object> { { "Content-type", "application/json; charset=utf-8" } }, Body = new { message = invalidRequestMessage } }); var result = ConsumerApiClient.ValidateDateTimeUsingProviderApi("lolz", _mockProviderServiceBaseUri).GetAwaiter().GetResult(); var resultBodyText = result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); Assert.Contains(invalidRequestMessage, resultBodyText); }
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(); }
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(); }
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 }
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(); }
public async void GivenUserIsNotAMember_WhenGetMembershipInvoked_ThenReturnsFalse() { _mockProviderService.Given("The userId1 is not a member") .UponReceiving("A GET request with userId1") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/users/userId1/memberships" }) .WillRespondWith(new ProviderServiceResponse { Status = 404 }); var request = new HttpRequestMessage(new HttpMethod("GET"), "/users/userId1/memberships/fellow"); var response = await Client.SendAsync(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var content = await response.Content.ReadAsStringAsync(); Assert.Equal("{\"member\":false}", content); }
public async Task Consumer_Gets_Three_Cars_From_Cars_Api() { _mockProviderService .Given("There are 3 cars") .UponReceiving("A GET request to retrieve car dtos") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/api/cars" }) .WillRespondWith(new ProviderServiceResponse { Status = 200, Headers = new Dictionary <string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = new List <CarDto> { new CarDto { Id = 1, Brand = "Volkswagen", Model = "Golf", Color = "Black" }, new CarDto { Id = 2, Brand = "Mercedes-Benz", Model = "A200", Color = "Grey" }, new CarDto { Id = 3, Brand = "Audi", Model = "Q5", Color = "Black" } } }); var httpClient = new HttpClient(); var response = await httpClient.GetAsync($"{_mockProviderServiceBaseUri}/api/cars"); var json = await response.Content.ReadAsStringAsync(); var cars = JsonConvert.DeserializeObject <List <CarDto> >(json); Assert.Equal(cars.Count, 3); }
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(); }
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); }
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(); }
public void GetAllEvents_WithNoAuthorizationToken_ShouldFail() { ContextInfo.SetTestContextName(GetType().Name); //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(); }