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

Add CompareJsonElementUsingJson extention #38

Merged
merged 1 commit into from
Sep 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/Atc.Test/EquivalencyAssertionOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,32 @@ public static EquivalencyAssertionOptions<T> CompareDateTimeUsingCloseTo<T>(
.Should()
.BeCloseTo(ctx.Expectation, precision))
.WhenTypeIs<DateTime>();

/// <summary>
/// Configures .BeEquivalentTo extensions to compare <see cref="JsonElement"/> by
/// comparing the underlying JSON string representation.
/// </summary>
/// <typeparam name="T">The generic parameter for the <see cref="EquivalencyAssertionOptions{T}"/>.</typeparam>
/// <param name="options">The <see cref="EquivalencyAssertionOptions{T}"/> to configure.</param>
/// <returns>The configured <see cref="EquivalencyAssertionOptions{T}"/>.</returns>
public static EquivalencyAssertionOptions<T> CompareJsonElementUsingJson<T>(
this EquivalencyAssertionOptions<T> options)
=> options.Using(new JsonElementEquivalencyStep());

private sealed class JsonElementEquivalencyStep : IEquivalencyStep
{
public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
{
if (comparands.Subject is not JsonElement subject ||
comparands.Expectation is not JsonElement expectation)
{
return EquivalencyResult.ContinueWithNext;
}

var newComparands = new Comparands(subject.GetRawText(), expectation.GetRawText(), typeof(string));
nestedValidator.RecursivelyAssertEquality(newComparands, context);

return EquivalencyResult.AssertionCompleted;
}
}
}