-
-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathJsonAssert.cs
More file actions
64 lines (58 loc) · 2.26 KB
/
JsonAssert.cs
File metadata and controls
64 lines (58 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Linq;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace GeoJSON.Net.Tests
{
/// <summary>
/// Assertions for json strings
/// </summary>
public static class JsonAssert
{
/// <summary>
/// Asserts that the json strings are equal.
/// </summary>
/// <remarks>
/// Parses each json string into a <see cref="JObject" />, sorts the properties of each
/// and then serializes each back to a json string for comparison.
/// </remarks>
/// <param name="expectJson">The expect json.</param>
/// <param name="actualJson">The actual json.</param>
public static void AreEqual(string expectJson, string actualJson)
{
Assert.That(
JObject.Parse(actualJson).SortProperties().ToString(), Is.EqualTo(JObject.Parse(expectJson).SortProperties().ToString()));
}
/// <summary>
/// Asserts that <paramref name="actualJson" /> contains <paramref name="expectedJson" />
/// </summary>
/// <param name="expectedJson">The expected json.</param>
/// <param name="actualJson">The actual json.</param>
public static void Contains(string expectedJson, string actualJson)
{
Assert.That(actualJson.Contains(expectedJson), $"expected {actualJson} to contain {expectedJson}");
}
/// <summary>
/// Sorts the properties of a JObject
/// </summary>
/// <param name="jObject">The json object whhose properties to sort</param>
/// <returns>A new instance of a <see cref="JObject" /> with sorted properties</returns>
private static JObject SortProperties(this JObject jObject)
{
var result = new JObject();
foreach (var property in jObject.Properties().OrderBy(p => p.Name))
{
var value = property.Value as JObject;
if (value != null)
{
value = value.SortProperties();
result.Add(property.Name, value);
}
else
{
result.Add(property.Name, property.Value);
}
}
return result;
}
}
}