-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomizeJsonSerialization.cs
More file actions
72 lines (56 loc) · 2.54 KB
/
Copy pathCustomizeJsonSerialization.cs
File metadata and controls
72 lines (56 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System.Net.Http.Json;
using System.Text.Json;
using static TestableHttpClient.Responses;
namespace TestableHttpClient.IntegrationTests;
public sealed class CustomizeJsonSerialization
{
[Fact]
public async Task ByDefault_CamelCasing_is_used_for_json_serialization()
{
using TestableHttpMessageHandler sut = new();
sut.RespondWith(Json(new { Name = "Charlie" }));
using HttpClient client = sut.CreateClient();
string json = await client.GetStringAsync("http://localhost/myjson", TestContext.Current.CancellationToken);
Assert.Equal("{\"name\":\"Charlie\"}", json);
}
[Fact]
public async Task But_this_can_be_changed()
{
using TestableHttpMessageHandler sut = new();
sut.Options.JsonSerializerOptions.PropertyNamingPolicy = null;
sut.RespondWith(Json(new { Name = "Charlie" }));
using HttpClient client = sut.CreateClient();
string json = await client.GetStringAsync("http://localhost/myjson", TestContext.Current.CancellationToken);
Assert.Equal("{\"Name\":\"Charlie\"}", json);
}
[Fact]
public async Task But_Also_directly_on_the_response()
{
using TestableHttpMessageHandler sut = new();
sut.RespondWith(Json(new { Name = "Charlie" }, jsonSerializerOptions: new JsonSerializerOptions()));
using HttpClient client = sut.CreateClient();
string json = await client.GetStringAsync("http://localhost/myjson", TestContext.Current.CancellationToken);
Assert.Equal("{\"Name\":\"Charlie\"}", json);
}
[Fact]
public async Task Asserting_also_works_this_way()
{
using TestableHttpMessageHandler sut = new();
using HttpClient client = sut.CreateClient();
await client.PostAsJsonAsync("http://localhost", new { Name = "Charlie" }, cancellationToken: TestContext.Current.CancellationToken);
sut.ShouldHaveMadeRequests(x => x.WithJsonContent(new { Name = "Charlie" }));
}
[Fact]
public async Task And_we_can_go_crazy_with_it()
{
using TestableHttpMessageHandler sut = new();
using HttpClient client = sut.CreateClient();
JsonSerializerOptions options = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
await client.PostAsJsonAsync("http://localhost", new { Name = "Charlie" }, options, cancellationToken: TestContext.Current.CancellationToken);
sut.ShouldHaveMadeRequests(x => x.WithJsonContent(new { Name = "Charlie" }, options));
}
}