1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nathano
  • 21
  • 3
  • Why are you defining a `PATCH` action method that doesn't accept a JSON patch request-body? - or enable the client to specify exactly which properties to set? As your method _always_ overwrites the `.Age` property your method should be `PUT`, imo. – Dai Jun 21 '23 at 16:09

1 Answers1

0

The UpdateAge(int id, int age, ...) handler will bind age parameter from query, so you will need URL like /people/1?age=42.

If you want endpoint to accept a JSON body then you should create a model for it, for example:

public record UpdateAgeRequest(int Age);

internal static async Task<IResult> UpdateAge(int id, UpdateAgeRequest request, ...)
{
    // ... implementation
}

Which will need the JSON body with age property:

var updatePersonAgeResult = await _client.PatchAsJsonAsync($"/people/{id}", new  
{
    age = newAge
}); 

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132