Skip to content

Commit fd10473

Browse files
committed
Add CompareJsonElementUsingJson extention to enable support for comparing JsonElement objects
1 parent eba6908 commit fd10473

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/Atc.Test/EquivalencyAssertionOptionsExtensions.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,32 @@ public static EquivalencyAssertionOptions<T> CompareDateTimeUsingCloseTo<T>(
4848
.Should()
4949
.BeCloseTo(ctx.Expectation, precision))
5050
.WhenTypeIs<DateTime>();
51+
52+
/// <summary>
53+
/// Configures .BeEquivalentTo extensions to compare <see cref="JsonElement"/> by
54+
/// comparing the underlying JSON string representation.
55+
/// </summary>
56+
/// <typeparam name="T">The generic parameter for the <see cref="EquivalencyAssertionOptions{T}"/>.</typeparam>
57+
/// <param name="options">The <see cref="EquivalencyAssertionOptions{T}"/> to configure.</param>
58+
/// <returns>The configured <see cref="EquivalencyAssertionOptions{T}"/>.</returns>
59+
public static EquivalencyAssertionOptions<T> CompareJsonElementUsingJson<T>(
60+
this EquivalencyAssertionOptions<T> options)
61+
=> options.Using(new JsonElementEquivalencyStep());
62+
63+
private sealed class JsonElementEquivalencyStep : IEquivalencyStep
64+
{
65+
public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
66+
{
67+
if (comparands.Subject is not JsonElement subject ||
68+
comparands.Expectation is not JsonElement expectation)
69+
{
70+
return EquivalencyResult.ContinueWithNext;
71+
}
72+
73+
var newComparands = new Comparands(subject.GetRawText(), expectation.GetRawText(), typeof(string));
74+
nestedValidator.RecursivelyAssertEquality(newComparands, context);
75+
76+
return EquivalencyResult.AssertionCompleted;
77+
}
78+
}
5179
}

0 commit comments

Comments
 (0)