Writing the Implementation
Let's pretend I have a Person
object:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
My Program.cs
file has the following minimal API endpoint
app.MapPatch("/people/{id}", MapApiEndpoints.UpdateAge)
And then the execution occurs in my MapApiEndpoints
class:
public class MapApiEndpoints
{
//
internal static async Task<Result> UpdateAge(int id, int age, PersonDbContext db)
{
var personToUpdate = await db.People.FindAsync(id);
if (personToUpdate is null) return TypedResults.NotFound();
personToUpdate.Age = age;
await db.SaveChangesAsync()
return TypedResults.NoContent();
}
}
Testing the Patch Request
How do I then test this endpoint? My test approach currently looks like this:
public async Task GivenAge_ThenPersonisUpdatedWithAge_AndSavedToDatabase()
{
// Create new Person
// save new Person to database
var newAge = 30;
var updatePersonAgeResult = await _client.PatchAsJsonAsync($"/people/{:id}, new
{
age = newAge
}
);
// get Person from database using same Id
// Assert whether Person.Age = newAge
}
The main confusion is how you pass along a new { }
object with the PatchAsJsonAsync
method.