Created
October 21, 2019 19:52
-
-
Save BlitzkriegSoftware/6fab86323ede3a424281c8a8e339c606 to your computer and use it in GitHub Desktop.
Test serialization of a DTO (if you have a REST API, please test it's DTOs)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// using Microsoft.VisualStudio.TestTools.UnitTesting; | |
// using Newtonsoft.Json; | |
// using System; | |
// using System.Collections.Generic; | |
// using System.Linq; | |
/// <summary> | |
/// Tests that a model serializes correctly | |
/// </summary> | |
/// <typeparam name="T">Type</typeparam> | |
/// <param name="thing1">Instance of T to test</param> | |
/// <param name="output">XUnit Test Output</param> | |
public static void AssertSerialization<T>(T thing1, TestContext output) | |
{ | |
var json = JsonConvert.SerializeObject(thing1); | |
output.WriteLine("{0} -> {1}", thing1.GetType().Name, json); | |
T thing2 = JsonConvert.DeserializeObject<T>(json); | |
Dictionary<String, Object> t1 = thing1.GetType() | |
.GetProperties() | |
.Where(p => p.CanRead) | |
.ToDictionary(p => p.Name, p => p.GetValue(thing1, null)); | |
Dictionary<String, Object> t2 = thing2.GetType() | |
.GetProperties() | |
.Where(p => p.CanRead) | |
.ToDictionary(p => p.Name, p => p.GetValue(thing2, null)); | |
foreach (var key in t1.Keys) | |
{ | |
var type = thing1.GetType(); | |
var mem = type.GetMember(key).First(); | |
if (!Attribute.IsDefined(mem, typeof(JsonIgnoreAttribute))) | |
{ | |
if (t1[key] != null) | |
{ | |
Assert.AreEqual(t1[key].ToString(), t2[key].ToString()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment