-
Notifications
You must be signed in to change notification settings - Fork 731
Closed
Labels
Description
Background and motivation
There is a separate package to assert on NewtonSoft.Json, but given that System.Text.Json is replacing the other more and more, I would expect me not being the only one who would like to see assertions that help testing JSON (de)serialization based on System.Text.Json.
I'm more than willing to help out to create a PR for such a feature, but before doing that (quite) some questions have to be answered.
- Should it be a separate package, or part of the core? (I would prefer the latter, as it is part of the core of .NET since 5.0)
- What is the object to assert on?
string,JsonElement,JsonSerializerOptions, or ...
For me personally, the most important use case is to write specs that guard the (overall) JSON serialization contract did not change. So something like:
namespace Serialization_Json;
public class Serializes
{
private readonly JsonSerializerSettings Settings = ...; // Whatever rows your boat.
[Test]
public void enum_values_by_name()
=> Settings.Serialize(NumberKind.One).Should().BeJsonString("One");
// Or
[Test]
public void enum_values_by_integer()
=> Settings.Serialize(NumberKind.One).Should().BeJsonNumber(1);
[Test]
public void models_skipping_null_properties()
=> Settings.Serialize(new Person { Name = null }).Should().BeJson("{}");
}
static class JsonSerializerOptionsExtensions
{
public static JsonElement Serialize<T>(this JsonSerializerOptions options, T value)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(value, options);
using var doc = JsonDocument.Parse(bytes );
return doc.RootElement.Clone();
}
}And obviously also for deserialize. But is this the kind of API that other users would also like to see? And if not, what kind of API to assert JSON (de)serialization is preferable?
Alternative Concerns
No response
martincostello, christopher-dabrowski, ProTip, andrearossiavanade, GREsau and 7 morexzxzxc, cluetjen, lucasteles and cjblomqvist