code_junkie

How to unit test if my object is really serializable?

Nov 11th, 2011
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. MyComplexObject dto = new MyComplexObject();
  2. MemoryStream mem = new MemoryStream();
  3. BinaryFormatter b = new BinaryFormatter();
  4. try
  5. {
  6. b.Serialize(mem, dto);
  7. }
  8. catch (Exception ex)
  9. {
  10. Assert.Fail(ex.Message);
  11. }
  12.  
  13. public static Stream Serialize(object source)
  14. {
  15. IFormatter formatter = new BinaryFormatter();
  16. Stream stream = new MemoryStream();
  17. formatter.Serialize(stream, source);
  18. return stream;
  19. }
  20.  
  21. public static T Deserialize<T>(Stream stream)
  22. {
  23. IFormatter formatter = new BinaryFormatter();
  24. stream.Position = 0;
  25. return (T)formatter.Deserialize(stream);
  26. }
  27.  
  28. public static T Clone<T>(object source)
  29. {
  30. return Deserialize<T>(Serialize(source));
  31. }
  32.  
  33. [Serializable]
  34. class Foo {
  35. public Bar MyBar { get; set; }
  36. }
  37.  
  38. [Serializable]
  39. class Bar {
  40. int x;
  41. }
  42.  
  43. class DerivedBar {
  44. }
  45.  
  46. public void TestSerializeFoo() {
  47. Serialize(new Foo()); // OK
  48. Serialize(new Foo() { MyBar = new Bar() }; // OK
  49. Serialize(new Foo() { MyBar = new DerivedBar() }; // Boom
  50. }
  51.  
  52. private static void AssertThatTypeAndPropertiesAreSerializable(Type type)
  53. {
  54. // base case
  55. if (type.IsValueType || type == typeof(string)) return;
  56.  
  57. Assert.IsTrue(type.IsSerializable, type + " must be marked [Serializable]");
  58.  
  59. foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  60. {
  61. if (propertyInfo.PropertyType.IsGenericType)
  62. {
  63. foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())
  64. {
  65. if (genericArgument == type) continue; // base case for circularly referenced properties
  66. AssertThatTypeAndPropertiesAreSerializable(genericArgument);
  67. }
  68. }
  69. else if (propertyInfo.GetType() != type) // base case for circularly referenced properties
  70. AssertThatTypeAndPropertiesAreSerializable(propertyInfo.PropertyType);
  71. }
  72. }
Add Comment
Please, Sign In to add comment