How to unit test if my object is really serializable?

后端 未结 7 1211
情书的邮戳
情书的邮戳 2020-12-03 00:45

I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of obj

7条回答
  •  死守一世寂寞
    2020-12-03 01:18

    Here is a solution that recursively uses IsSerializable to check that the object and all its properties are Serializable.

        private static void AssertThatTypeAndPropertiesAreSerializable(Type type)
        {
            // base case
            if (type.IsValueType || type == typeof(string)) return;
    
            Assert.IsTrue(type.IsSerializable, type + " must be marked [Serializable]");
    
            foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (propertyInfo.PropertyType.IsGenericType)
                {
                    foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())
                    {
                        if (genericArgument == type) continue; // base case for circularly referenced properties
                        AssertThatTypeAndPropertiesAreSerializable(genericArgument);
                    }
                }
                else if (propertyInfo.GetType() != type) // base case for circularly referenced properties
                    AssertThatTypeAndPropertiesAreSerializable(propertyInfo.PropertyType);
            }
        }
    

提交回复
热议问题