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
Comments
Analysis:
As the This behavior can be seen with element1.Equals(element2); // false Workaround: element1.Should().BeEquivalentTo(element2, opt => opt.ComparingByMembers<JsonElement>()); |
Hi @jnyrup, Thank you for the prompt reply. |
Structural comparison here means comparing the values of the members of the objects. |
Is there a workaround for when comparing objects that contain |
@stewie1570 The workaround described above works as well for objects containing 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>()*/);
} |
And we also have |
@dennisdoomen |
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
This handles when actual/expected are some aggregate class with a |
Test is failing when comparing two Json Elements using
ShouldBeEquivalentTo
. I'm sure that this AssertionExpected 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
The text was updated successfully, but these errors were encountered: