/// <summary> /// Tests that a specific property is deserialized correctly. /// </summary> /// <param name="item">The item containing the current value.</param> /// <param name="property">The property to inspect.</param> /// <param name="testValue">The test value, must not match the current value.</param> /// <typeparam name="TValue"></typeparam> protected void TestThatPropertyIsDeserialized <TValue>(TInterface item, Expression <Func <TInterface, TValue> > property, TValue testValue) { // params cannot be null. Assert.NotNull(item); Assert.NotNull(property); // member expression must be a property expression. var prop = GetPropertyInfo(property); Assert.NotNull(prop); AdjustProperties(item); // property must be in the list of deserialized properties var propInfo = Properties.FirstOrDefault(x => x.Deserialize && x.Property.Name == prop.Name); Assert.NotNull(propInfo); // test value must differ from current value. Assert.NotEqual(testValue, prop.GetValue(item)); var jo = JObject.FromObject(item); if (propInfo.Serialize) { // property should be in serialized JSON. Assert.True(jo.ContainsKey(propInfo.Name)); } else { // property should not be in serialized JSON. Assert.False(jo.ContainsKey(propInfo.Name)); } // set property in serialized JSON. if (testValue.GetType().IsPrimitive || testValue is string || testValue is DateTime || testValue is Guid) { jo[propInfo.Name] = new JValue(testValue); } else { jo[propInfo.Name] = JObject.FromObject(testValue); } Assert.True(jo.ContainsKey(propInfo.Name)); // deserialize the object. var type = InternalModel.TypeFor(typeof(TInterface)); var newItem = jo.ToObject(type) as TInterface; Assert.NotNull(newItem); // the new object should have the test value. Assert.Equal(testValue, prop.GetValue(newItem)); // the original object should not. Assert.NotEqual(testValue, prop.GetValue(item)); }
protected Model_Should() { ModelType = InternalModel.TypeFor(InterfaceType); var tmp = InterfaceType .GetProperties(BindingFlags.Public | BindingFlags.Instance) .OrderBy(x => x.Name) .Select(x => new PropInfo() { Property = x }) .ToArray(); foreach (var p in tmp) { var sib = ModelType.GetProperty(p.Property.Name); var attr = sib?.GetCustomAttribute <JsonPropertyAttribute>(); p.Name = attr?.PropertyName ?? p.Property.Name; p.Deserialize = p.Property.CanRead && (sib.GetCustomAttribute <JsonIgnoreAttribute>() is null); p.Serialize = p.Deserialize && p.Property.CanWrite; } Properties = tmp.Cast <IPropInfo>().ToArray(); }