Skip to content

Instantly share code, notes, and snippets.

@tonysneed
Created January 28, 2022 00:29
Show Gist options
  • Save tonysneed/007bef31a9c544620a37360b0b87ee0a to your computer and use it in GitHub Desktop.
Save tonysneed/007bef31a9c544620a37360b0b87ee0a to your computer and use it in GitHub Desktop.
[Binding]
public class WeatherWebApiStepDefinitions
{
private const string BaseAddress = "http://localhost/";
public WebApplicationFactory<Program> Factory { get; }
public IWeatherRepository Repository { get; }
public HttpClient Client { get; set; } = null!;
private HttpResponseMessage Response { get; set; } = null!;
public JsonFilesRepository JsonFilesRepo { get; }
private WeatherForecast? Entity { get; set; }
private JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions
{
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true
};
public WeatherWebApiStepDefinitions(
WebApplicationFactory<Program> factory,
IWeatherRepository repository,
JsonFilesRepository jsonFilesRepo)
{
Factory = factory;
Repository = repository;
JsonFilesRepo = jsonFilesRepo;
}
[Given(@"I am a client")]
public void GivenIAmAClient()
{
Client = Factory.CreateDefaultClient(new Uri(BaseAddress));
}
[Given(@"the repository has weather data")]
public async Task GivenTheRepositoryHasWeatherData()
{
var weathersJson = JsonFilesRepo.Files["weathers.json"];
var weathers = JsonSerializer.Deserialize<IList<WeatherForecast>>(weathersJson, JsonSerializerOptions);
if (weathers != null)
foreach (var weather in weathers)
await Repository.AddAsync(weather);
}
[When(@"I make a GET request with id '(.*)' to '(.*)'")]
public async Task WhenIMakeAgetRequestWithIdTo(int id, string endpoint)
{
Response = await Client.GetAsync($"{endpoint}/{id}");
}
[When(@"I make a POST request with '(.*)' to '(.*)'")]
public async Task WhenIMakeApostRequestWithTo(string file, string endpoint)
{
var json = JsonFilesRepo.Files[file];
var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
Response = await Client.PostAsync(endpoint, content);
}
[Then(@"the response status code is '(.*)'")]
public void ThenTheResponseStatusCodeIs(int statusCode)
{
var expected = (HttpStatusCode)statusCode;
Assert.Equal(expected, Response.StatusCode);
}
[Then(@"the location header is '(.*)'")]
public void ThenTheLocationHeaderIs(Uri location)
{
Assert.Equal(location, Response.Headers.Location);
}
[Then(@"the response json should be '(.*)'")]
public async Task ThenTheResponseDataShouldBe(string file)
{
var expected = JsonFilesRepo.Files[file];
var response = await Response.Content.ReadAsStringAsync();
var actual = response.JsonPrettify();
Assert.Equal(expected, actual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment