/src/UnitTests/Proxy/ProxySerializationTests.cs

http://github.com/philiplaureano/LinFu · C# · 62 lines · 48 code · 10 blank · 4 comment · 2 complexity · 0339578a233fc7ee47e6879de9ef9629 MD5 · raw file

  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Runtime.Serialization;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using LinFu.AOP.Cecil;
  8. using LinFu.Proxy;
  9. using LinFu.Proxy.Interfaces;
  10. using Xunit;
  11. using SampleLibrary;
  12. using SampleLibrary.Proxy;
  13. namespace LinFu.UnitTests.Proxy
  14. {
  15. public class ProxySerializationTests : BaseTestFixture
  16. {
  17. [Fact]
  18. public void ShouldSupportSerialization()
  19. {
  20. var factory = new ProxyFactory();
  21. var interceptor = new SerializableInterceptor();
  22. interceptor.Identifier = Guid.NewGuid();
  23. var proxy = factory.CreateProxy<ISampleService>(interceptor);
  24. var proxyType = proxy.GetType();
  25. var proxyAssembly = proxyType.Assembly.Location;
  26. // The proxy type should have a default constructor
  27. // and a serialization constructor
  28. var constructorFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  29. var constructors = proxyType.GetConstructors(constructorFlags);
  30. Assert.True(constructors.Length == 2);
  31. var serializationConstructor = proxyType.GetConstructor(constructorFlags, null,
  32. new[]
  33. {
  34. typeof(SerializationInfo),
  35. typeof(StreamingContext)
  36. }, null);
  37. Assert.NotNull(serializationConstructor);
  38. // Serialize the proxy
  39. var stream = new MemoryStream();
  40. var formatter = new BinaryFormatter();
  41. formatter.Serialize(stream, proxy);
  42. // Deserialize the proxy from the stream
  43. stream.Seek(0, SeekOrigin.Begin);
  44. var restoredProxy = (IProxy) formatter.Deserialize(stream);
  45. Assert.NotNull(restoredProxy);
  46. Assert.NotNull(restoredProxy.Interceptor);
  47. Assert.True(restoredProxy.Interceptor.GetType() == typeof(SerializableInterceptor));
  48. var otherInterceptor = (SerializableInterceptor) restoredProxy.Interceptor;
  49. Assert.Equal(otherInterceptor.Identifier, interceptor.Identifier);
  50. }
  51. }
  52. }