Skip to content

Conversation

maxkagamine
Copy link
Owner

@maxkagamine maxkagamine commented Jul 4, 2022

Long-overdue System.Text.Json extensions!

The new ReturnsJsonResponse methods (named so due to being otherwise ambiguous) are functionally similar to the System.Net.Http.Json extensions, PostAsJsonAsync() etc., and send a JsonContent instead of StringContent.

Example usage (see ResponseExtensionsTests):

List<Song> expected = /* ... */;

handler.SetupRequest(HttpMethod.Get, "https://example.com/api/songs")
    .ReturnsJsonResponse(expected);

var actual = await client.GetFromJsonAsync<List<Song>>("api/songs");

actual.Should().BeEquivalentTo(expected);

RequestExtensionsTests has also been updated with examples of using System.Text.Json to match requests:

handler
    .SetupRequest(HttpMethod.Post, url, async request =>
    {
        var json = await request.Content.ReadFromJsonAsync<Model>();
        return json.Id == expected.Id;
    })
    .ReturnsResponse(HttpStatusCode.Created);

Or if you know the code under test is using the System.Text.Json extensions:

handler
    .SetupRequest(HttpMethod.Post, url, r => ((JsonContent)r.Content).Value == model)
    .ReturnsResponse(HttpStatusCode.Created);

This pairs especially well with record types.

@maxkagamine maxkagamine force-pushed the json branch 5 times, most recently from c3fe2fc to 244b4e3 Compare July 9, 2022 05:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant