|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Should; |
| 7 | +using Xunit; |
| 8 | +using System.Reflection; |
| 9 | +using Newtonsoft.Json.Serialization; |
| 10 | +using Newtonsoft.Json; |
| 11 | + |
| 12 | +namespace CollectionJson.Client.Tests |
| 13 | +{ |
| 14 | + public class CollectionJsonContractResolverTest |
| 15 | + { |
| 16 | + private CollectionJsonContractResolver _resolver = new CollectionJsonContractResolver(); |
| 17 | + private Func<MemberInfo, CollectionJsonContractResolver, MemberSerialization, JsonProperty> _createProperty; |
| 18 | + private PropertyInfo _itemsProperty; |
| 19 | + private PropertyInfo _versionProperty; |
| 20 | + |
| 21 | + public CollectionJsonContractResolverTest() |
| 22 | + { |
| 23 | + var method = _resolver.GetType().GetMethod("CreateProperty", BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic); |
| 24 | + _createProperty = (m, r, s) => |
| 25 | + { |
| 26 | + return (JsonProperty) method.Invoke(r, new object[] {m, s}); |
| 27 | + }; |
| 28 | + var collType = typeof(Collection); |
| 29 | + _itemsProperty = collType.GetProperty("Items", BindingFlags.Instance | BindingFlags.Public); |
| 30 | + _versionProperty = collType.GetProperty("Version", BindingFlags.Instance | BindingFlags.Public); |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + [Fact] |
| 35 | + public void WhenPropertyIsListAndItHasNoItemsItWillNotBeSerialized() |
| 36 | + { |
| 37 | + var collection = new Collection(); |
| 38 | + var prop = _createProperty(_itemsProperty, _resolver, MemberSerialization.OptOut); |
| 39 | + prop.ShouldSerialize(collection).ShouldBeFalse(); |
| 40 | + } |
| 41 | + |
| 42 | + [Fact] |
| 43 | + public void WhenPropertyIsListAndIsHasItemsItWillBeSerialized() |
| 44 | + { |
| 45 | + var collection = new Collection(); |
| 46 | + collection.Items.Add(new Item()); |
| 47 | + var prop = _createProperty(_itemsProperty, _resolver, MemberSerialization.OptOut); |
| 48 | + prop.ShouldSerialize(collection).ShouldBeTrue(); |
| 49 | + } |
| 50 | + |
| 51 | + [Fact] |
| 52 | + public void WhenPropertyIsNotListItWillBeSerialized() |
| 53 | + { |
| 54 | + var collection = new Collection(); |
| 55 | + var prop = _createProperty(_versionProperty, _resolver, MemberSerialization.OptOut); |
| 56 | + prop.ShouldSerialize(collection).ShouldBeTrue(); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments