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.

1
  • 1
    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. Commented Jun 21, 2023 at 16:09

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.