PosInformatique.FluentAssertions.Json 1.4.0

Prefix Reserved
dotnet add package PosInformatique.FluentAssertions.Json --version 1.4.0                
NuGet\Install-Package PosInformatique.FluentAssertions.Json -Version 1.4.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PosInformatique.FluentAssertions.Json" Version="1.4.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PosInformatique.FluentAssertions.Json --version 1.4.0                
#r "nuget: PosInformatique.FluentAssertions.Json, 1.4.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PosInformatique.FluentAssertions.Json as a Cake Addin
#addin nuget:?package=PosInformatique.FluentAssertions.Json&version=1.4.0

// Install PosInformatique.FluentAssertions.Json as a Cake Tool
#tool nuget:?package=PosInformatique.FluentAssertions.Json&version=1.4.0                

PosInformatique.FluentAssertions.Json

PosInformatique.FluentAssertions.Json is a library to assert JSON serialization using the Fluent Assertions library style coding.

Nuget

Installing from NuGet

The PosInformatique.FluentAssertions.Json library is available directly on the Nuget official website.

To download and install the library to your Visual Studio unit test projects use the following NuGet command line

Install-Package PosInformatique.FluentAssertions.Json

How it is work?

Imagine that you have the following JSON class:

public class Customer
{
    [JsonPropertyName("id")]
    [JsonPropertyOrder(1)]
    public int Id { get; set; }

    [JsonPropertyName("name")]
    [JsonPropertyOrder(2)]
    public string Name { get; set; }

    [JsonPropertyName("gender")]
    [JsonPropertyOrder(3)]
    public Gender Gender { get; set; }
}

public enum Gender
{
    None = 0,
    Male = 100,
    Female = 200,
}

With the following instance:

var customer = new Customer()
{
    Id = 1234,
    Name = "Gilles TOURREAU",
    Gender = Gender.Male,
};

You would like to check this class is serializable into the following JSON object:

{
    "id": 1234,
    "name": "Gilles TOURREAU",
    "gender": 100,
}

Using standard assertions you should write the following code 😨:

[Fact]
public void Serialization()
{
    var customer = new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    };

    var json = JsonSerializer.Serialize(customer);

    json.Should().Be("{\"id\":1234,\"name\":\"Gilles TOURREAU\",\"gender\":100}");
    
    // Or
    json.Should().Be(@"{""id"":1234,""name"":""Gilles TOURREAU"",""gender"":100}");
}

With the following kind of exception when the unit test is incorrect: Ugly exception

As you can see the previous code is not sexy to read (and to write!) and the exception is hard to understand...

Test the serialization of a .NET Object to a JSON object.

With the new fluent style using this library you can write previous unit test like that:

[Fact]
public void Serialization()
{
    var customer = new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    };

    customer.Should().BeJsonSerializableInto(new
    {
        id = 1234,
        name = "Gilles TOURREAU",
        gender = 100,
    });
}

And when an exception is occured, the exception message contains the JSON path of the property which is error: Pretty exception

Test the deserialization of a JSON object to a .NET Object

You can in the same way test the deserialization JSON object into a .NET object.

[Fact]
public void Deserialization()
{
    var json = new
    {
        id = 1234,
        name = "Gilles TOURREAU",
        gender = 100,
    };

    json.Should().BeJsonDeserializableInto(new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    });
}

Test polymorphisme serialization with property discriminator

With the .NET 7.0 version of the System.Text.Json it is possible to serialize and deserialize JSON object with property discriminators for polymorphism scenario (See the How to serialize properties of derived classes with System.Text.Json) topic for more information.

It is possible also to use the polymorphism JSON serialization with previous version of .NET using a custom JsonConverter. See the How to serialize properties of derived classes with System.Text.Json (.NET 6.0) for more information.

Imagine you have the following classes hierarchy:

[JsonPolymorphic(TypeDiscriminatorPropertyName = "type")]
[JsonDerivedType(typeof(ThreeDimensionalPoint), typeDiscriminator: "3d")]
private class BasePoint
{
    [JsonPropertyOrder(1)]
    public int X { get; set; }

    [JsonPropertyOrder(2)]
    public int Y { get; set; }
}

private class ThreeDimensionalPoint : BasePoint
{
    [JsonPropertyOrder(3)]
    public int Z { get; set; }
}

And you would like to assert that the serialization of ThreeDimensionalPoint instance generate the following JSON content when calling the JsonSerializer.Serialize<T>() method with BasePoint as generic argument:

var point = new ThreeDimensionalPoint()
{
    X = 1,
    Y = 2,
    Z = 3,
}

var json = JsonSerializer.Serialize<BasePoint>();
{
    "type": "3d",
    "X": 1,
    "Y": 2,
    "Z": 3, 
}

This is the assertion to write using the PosInformatique.FluentAssertions.Json library:

point.Should().BeJsonSerializableInto<BasePoint>(new
{
    myType = "3d",
    X = 1,
    Y = 2,
    Z = 3,
});

NOTE: If you don't specify the BasePoint generic argument, the library will use the default behavior of the JsonSerializer.Serialize() (with no generic argument), which will generate (and assert!) the following JSON object:

{
   "X": 1,
   "Y": 2,
   "Z": 3, 
}

As you can see there is no discriminator property generate because the .NET JsonSerializer.Serialize() will use the type of the instance instead of an explicit type of derived class.

Change the JsonSerializer options

Change globally the JsonSerializer options

The JSON serialization and deserialization assertions use the default instance of the JsonSerializerOptions.

It is possible to change globally this default options by accessing to the static instance of FluentAssertionsJson.Configuration.JsonSerializerOptions.

For example, if you use xUnit test engine and you want to apply the JsonStringEnumConverter for all the unit tests in the PosInformatique.JsonModels.Tests, create the following xUnit extensions class and apply the assembly XunitTestFrameworkAttribute to reference this class:

[assembly: TestFramework("PosInformatique.JsonModels.Tests.JsonModelsTestFramework", "PosInformatique.JsonModels.Tests")]

namespace PosInformatique.JsonModels.Tests
{
    using System.Text.Json.Serialization;
    using PosInformatique.FluentAssertions.Json;
    using Xunit.Abstractions;
    using Xunit.Sdk;

    public class JsonModelsTestFramework : XunitTestFramework
    {
        public FunctionsTestFramework(IMessageSink messageSink)
            : base(messageSink)
        {
            FluentAssertionsJson.Configuration.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        }
    }
}

Defines the JsonSerializer options specifically on an unit test.

It is possible when calling the BeJsonSerializableInto() and BeJsonDeserializableInto() methods to specify the JsonSerializerOptions used for the serialization and deserialization process during the assertion.

For example, to use the JsonStringEnumConverter to serialize the enum into a string value:

[Fact]
public void Serialization()
{
    var customer = new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    };

    var options = new JsonSerializerOptions()
    {
        new JsonStringEnumConverter(),
    };

    customer.Should().BeJsonSerializableInto(new
    {
        id = 1234,
        name = "Gilles TOURREAU",
        gender = "Male",
    },
    options);
}

[Fact]
public void Deserialization()
{
    var json = new
    {
        id = 1234,
        name = "Gilles TOURREAU",
        gender = "Male",
    };

    var options = new JsonSerializerOptions()
    {
        new JsonStringEnumConverter(),
    };

    json.Should().BeJsonDeserializableInto(new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    },
    options);
}

Changes the global JsonSerializerOptions for a specific assertion.

It is possible to changes the global FluentAssertionsJson.Configuration.JsonSerializerOptions for a specific assertion using a configuration lambda expression.

For example, if you have defines globally the JsonStringEnumConverter converter for all the unit tests (see the previous examples), but you would like to remove the existing converter in the specific unit tests:

[Fact]
public void Serialization()
{
    var customer = new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    };

    customer.Should().BeJsonSerializableInto(new
    {
        id = 1234,
        name = "Gilles TOURREAU",
        gender = "Male",
    },
    opt =>
    {
        opt.Converters.Clear();
    });
}

[Fact]
public void Deserialization()
{
    var json = new
    {
        id = 1234,
        name = "Gilles TOURREAU",
        gender = "Male",
    };

    var options = new JsonSerializerOptions()
    {
        new JsonStringEnumConverter(),
    };

    json.Should().BeJsonDeserializableInto(new Customer()
    {
        Id = 1234,
        Name = "Gilles TOURREAU",
        Gender = Gender.Male,
    },
    opt =>
    {
        opt.Converters.Clear();
    });
}

NOTE: The lambda expression allows to update the global FluentAssertionsJson.Configuration.JsonSerializerOptions instance during the call of the BeJsonSerializableInto() or BeJsonDeserializableInto() methods. Global previous JsonSerializerOptions will be restored at the end of the assertion.

Library dependencies

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on PosInformatique.FluentAssertions.Json:

Package Downloads
PosInformatique.Testing.Azure.Functions.Http

This project provides utilities for testing Azure Functions (Isolated). It includes features and tools to facilitate the testing of HttpRequestData and HttpResponseData classes, which are challenging to mock.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.4.0 94 10/28/2024
1.4.0-rc.1 40 10/28/2024
1.3.0 352 6/28/2024
1.3.0-rc.1 53 6/18/2024
1.2.0 1,305 10/29/2023
1.1.0 158 10/25/2023
1.0.5 184 10/15/2023
1.0.4 166 10/15/2023
1.0.3 152 10/13/2023
1.0.2 169 10/11/2023
1.0.1 194 10/10/2023
1.0.0 167 10/10/2023

1.4.0
     - Add new overload BeJsonDeserializableInto() method to test if a Stream contains a JSON serializable object.

     1.3.0
     - Add new overload BeJsonDeserializableInto() method to test the string collections.
     - Add new overload BeJsonDeserializableInto() method to test the string and numeric values.

     1.2.0
     - Add new overload BeJsonSerializableInto() method to test polymorphism serialization with discriminator JSON property.
     - Add the support to assert the deserialization of root JSON array.

     1.1.0
     - Allows to configure the JsonSerializationOptions globally and in specific assertions calls.

     1.0.5
     - Use the FluentAssertions library version 6.0.0 instead of 5.0.0 to fix breaking changes of the API.

     1.0.4
     - Ignore the properties with the [JsonIgnore] attribute.

     1.0.3
     - Target the .NET Standard 2.0 instead of .NET Core 6.0

     1.0.2
     - Fix the README.md file.

     1.0.1
     - Various fixes for the NuGet package description.

     1.0.0
     - Initial version