Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BeEquivalentTo fails when comparing two JsonElement's #1212

Closed
annas-abuhassan opened this issue Dec 30, 2019 · 8 comments
Closed

BeEquivalentTo fails when comparing two JsonElement's #1212

annas-abuhassan opened this issue Dec 30, 2019 · 8 comments

Comments

@annas-abuhassan
Copy link

annas-abuhassan commented Dec 30, 2019

Test is failing when comparing two Json Elements using ShouldBeEquivalentTo. I'm sure that this Assertion

[Fact]
public void Test()
{
    // Arrange & Act
    var element1 = JsonDocument.Parse("{}").RootElement;
    var element2 = JsonDocument.Parse("{}").RootElement;

    // Assert
    element1.Should().BeEquivalentTo(element2);
}

Expected behavior:

I would expect this to pass

Actual behavior:

This actually fails

Versions

XUnit v2.4.1
FluentAssertions v5.9.0
.NET Core 3.0

@jnyrup
Copy link
Member

jnyrup commented Dec 30, 2019

Analysis:
JsonElement is a struct that does not override Object.Equals(object).
That is, it keeps the default generated ValueType.Equals(object) which compares instances memberwise using their Equals(object).

JsonElement has a field _parent, which points to its parent JsonDocument.
JsonDocument also does not override Object.Equals(object), so instances are compared by reference.

As the _parent fields of element1 and element2 points to two different JsonDocuments in memory, element1 does not equal element2.

This behavior can be seen with

element1.Equals(element2); // false

Workaround:
If you use ComparingByMembers() Fluent Assertions will compare object structurally (think memberwise), but per default only for public members.
So it will now exclude _parent.

element1.Should().BeEquivalentTo(element2, opt => opt.ComparingByMembers<JsonElement>());

@annas-abuhassan
Copy link
Author

Hi @jnyrup,

Thank you for the prompt reply.
So I cannot compare JsonElements values, only the structure of the object - is that correct?

@jnyrup
Copy link
Member

jnyrup commented Dec 31, 2019

Structural comparison here means comparing the values of the members of the objects.

@stewie1570
Copy link

stewie1570 commented Dec 3, 2020

Is there a workaround for when comparing objects that contain JsonElement(s)?

@jnyrup
Copy link
Member

jnyrup commented Dec 3, 2020

@stewie1570 The workaround described above works as well for objects containing JsonElements.

public void TestMethod1()
{
    // Arrange & Act
    var element1 = new { Json = JsonDocument.Parse("{}").RootElement };
    var element2 = new { Json = JsonDocument.Parse("{}").RootElement };

    // Assert
    element1.Should().BeEquivalentTo(element2, opt => opt
        /*.ComparingByMembers<JsonElement>()*/);
}

@dennisdoomen
Copy link
Member

And we also have FluentAssertions.Json

@jnyrup
Copy link
Member

jnyrup commented Dec 3, 2020

@dennisdoomen JsonElement is from System.Text.Json not Newtonsoft.Json.

@jevonkendon
Copy link

jevonkendon commented Mar 24, 2021

For now I've created a custom FluentAssertion rule, which just compares their string representations:

public class JsonDocumentRule : IAssertionRule
{
    public bool AssertEquality(IEquivalencyValidationContext context)
    {
        if (!(context.Subject is JsonDocument subjectValue) ||
            !(context.Expectation is JsonDocument expectationValue))
        {
            // rule not applicable
            return false;
        }

        var lhs = ToJsonString(subjectValue);
        var rhs = ToJsonString(expectationValue);

        Execute.Assertion
            .BecauseOf(context.Because, context.BecauseArgs)
            .ForCondition(lhs == rhs)
            .FailWith("Expected {context:string} to be {0}{reason}, but found {1}",
                context.Subject, context.Expectation);

        // equality assertion handled
        return true;
    }

    private static string ToJsonString(JsonDocument document)
    {
        using var stream = new MemoryStream();
        Utf8JsonWriter writer = new Utf8JsonWriter(stream, new JsonWriterOptions {Indented = true});
        document.WriteTo(writer);
        writer.Flush();
        return Encoding.UTF8.GetString(stream.ToArray());
    }
}

and then

actual.Should().BeEquivalentTo(expected, options => options.Using(new JsonDocumentRule()));

This handles when actual/expected are some aggregate class with a JsonDocument member.

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

No branches or pull requests

5 participants